Nasr
Nasr

Reputation: 2632

Repeat function if error happens in node.js

I want to call a function in node.js but most likely this function will have an error in it's callback, i want to know the best way to repeat this function number of speciefied time.

Is this way good enought or there is better?

var numberOfRetrials = 0;
do{
    send_bus(15, function(err){    // send_bus is synchronus function
        check = err;
    });
    numberOfRetrials++;
} while( (check != null) && (numberOfRetrials <3) );

Upvotes: 0

Views: 1788

Answers (2)

Alfonso Presa
Alfonso Presa

Reputation: 1034

Try:

var numberOfRetrials = 0;

var task = function () {
    send_bus(15, function(err){
        if(err && numberOfRetrials++ <3){
            task();
        }
    });
};
task();

This will work both for sync or async tasks functions. It's a recursive function with an exit condition based in a counter.

Upvotes: 2

beautifulcoder
beautifulcoder

Reputation: 11340

Really, since it looks asynchronous to me. I would not put the logic in a loop:

var count = 0;
function cb(err) {
    if (!err && count < 3) {
        count++;
        send_bus(15, cb);
    }
}
send_bus(15, cb);

Upvotes: 1

Related Questions