Last Updated: February 25, 2016
·
10.1K
· deleteman

Make a js function retry N times before giving up

Following the convention that:

  • For a giving function, the last argument is a callback
  • And for that callback, the first argument is the error. This function allows us to get our original function to retry itself N times whenever there is failure (when the first argument of the callback is true) before giving up. It overrides the original callback function in order to test for the value of the first argument until it is false (no error) or the retry cap is reached.

Example:

var testFunc = function(param1, cb) {
  var result = //service request that tends to be unstable
  var err = result == null;
  cb(err, result);
 };

 //Doing..
testFunc("test", function(err, result) {
    //Here we'll have to handle the error that happens when the service is unstable
});

//But by doing
var retryTest = _.retry(5, testFunc);
retryTest("test", function(err, result) {
      //It'll retry 5 times before giving up and calling this callback, if one of those times, the service works, it'll return a valid response instead of the error.
});

Pull Request to see the code: https://github.com/documentcloud/underscore/pull/1061