Skip to content

Instantly share code, notes, and snippets.

@kjvalencik
Last active August 29, 2015 14:22
Show Gist options
  • Save kjvalencik/5c97dd00337bdca51ebf to your computer and use it in GitHub Desktop.
Save kjvalencik/5c97dd00337bdca51ebf to your computer and use it in GitHub Desktop.
Bluebird Promise Re-try
function promiseRetry(_fn, _attempts, backoff /* , errTypes */) {
var fn = Bluebird.method(_fn),
attempts = parseInt(_attempts, 10);
var argsLen = arguments.length,
retryLen = promiseRetry.length,
catchArgs = new Array(Math.max(1, argsLen - retryLen + 1));
for (var i = retryLen; i < argsLen; i += 1) {
catchArgs[i - retryLen] = arguments[i];
}
catchArgs[catchArgs.length - 1] = waitTry;
function waitTry(err) {
return Bluebird.delay(backoff)
.return(err)
.then(tryAgain);
}
function tryAgain(err) {
if (!isNaN(attempts) && attempts-- <= 0) {
throw err;
}
return Bluebird.prototype.catch.apply(fn(), catchArgs);
}
return Bluebird.try(tryAgain);
}
promiseRetry(doSomething, 5, 200).then(function (result) {
console.log(result);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment