Skip to content

Instantly share code, notes, and snippets.

@neilk
Last active June 9, 2017 23:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save neilk/2c69743b22f84605e3d255056ee56c09 to your computer and use it in GitHub Desktop.
Save neilk/2c69743b22f84605e3d255056ee56c09 to your computer and use it in GitHub Desktop.
Retry logic for promises
/**
* Retry a promise until success, up to a certain number of times.
* Returns the last error if it reaches maximum attempts.
*
* @param maxTries {Number} positive integer
* @param p {Promise}
* @return {Promise}
*/
function retry (maxTries, p) {
var tries = 0;
var iter = function() {
tries++;
return p().catch(function(error) {
console.log(">>> Errored on try " + tries + "/" + maxTries)
if (tries >= maxTries) {
return Promise.reject(error);
} else {
return iter();
}
});
};
return iter();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment