Example of retry for operations that use EventEmitter and not Callback
Closed this issue · 7 comments
What is the right way of using node-retry for operations that use EventEmitter for 'error' events, rather than callback?
Hey Michal,
sorry for the long delay here, but I was on vacation.
Could you please provide some example code?
Best,
Tim
Hey @michaelkariv
Did you see my reply?
@michaelkariv I think it's working the same way. Assuming you have a task
object, which is an Event Listener emitting errors, and starting processing stuff after calling execute()
:
var operation = retry.operation();
var t = new Task();
t.on('error', function(err) {
operation.retry(err);
});
operation.attempt(function (currentAttempt) {
t.execute();
});
Closing this. Feel free to re-open if our comments did not help.
Based on @tim-kos answer here is a complete sample that checks for RabbitMQ + MongoDb connection using net
and only continues code exection when both connections are available.
var net = require('net');
var retry = require('retry');
var async = require('async');
function tryConnect(HOST, PORT, cb) {
var client = new net.Socket();
var operation = retry.operation();
var cbCalled = false;
client.on('error', function(err) {
console.log('error');
operation.retry(err);
});
operation.attempt(function (currentAttempt) {
client.connect(PORT, HOST, function(){
console.log('CONNECTED TO: ' + HOST + ':' + PORT);
if(!cbCalled) {
cb();
cbCalled = true;
}
});
});
}
async.parallel(
[
function(cb) {
tryConnect('localhost', 5672, cb);
},
function(cb) {
tryConnect('localhost', 27017, cb);
}
],
function() {
console.log('both connected')
}
)
@tim-kos Given the example above: How would I call the callback with an error if retry options are { retries : 2, factor: 1 }
and the call eventually fails in the end?
Got it:
if(!operation.retry(err)) {
cb(err, null)
}