Skip to content

Instantly share code, notes, and snippets.

@dgoguerra
Last active September 5, 2016 12:10
Show Gist options
  • Save dgoguerra/8ac0c4293595e87567957befad4a786a to your computer and use it in GitHub Desktop.
Save dgoguerra/8ac0c4293595e87567957befad4a786a to your computer and use it in GitHub Desktop.
retry an async action until it doesn't fail
// attempt to do an async action in a loop, until it doesn't
// return an error or a max number of retries is reached.
function attempt(opts, fun, next) {
var lastError = null, retry = 0,
increment = opts.increment || 500,
nextTimeout = typeof opts.initial !== 'undefined' ? opts.initial : 500,
maxRetries = typeof opts.retries !== 'undefined' ? opts.retries : 0;
function nextRetry() {
if (maxRetries && retry >= maxRetries) {
return next(lastError);
}
retry++;
setTimeout(function() {
fun(function(err, res) {
if (err) {
lastError = err;
return nextRetry();
}
next(null, res);
});
}, nextTimeout);
nextTimeout += increment;
}
nextRetry();
}
@dgoguerra
Copy link
Author

usage example:

var retry = 0;
attempt({initial: 0, increment: 100, retries: 8}, function(next) {
  if (++retry < 5) {
    return next(new Error('action failed'));
  }

  var results = {foo: 'bar', num: retry};
  next(null, results);
}, function(err, results) {
  if (err) {
    console.error('error: too many attempts without success');
    console.error('error: '+err.message);
    return;
  }

  console.log('success in retry '+results.num+', foo: '+results.foo);
});

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment