Last active
August 29, 2015 14:22
-
-
Save kjvalencik/5c97dd00337bdca51ebf to your computer and use it in GitHub Desktop.
Bluebird Promise Re-try
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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