Last active
June 9, 2017 23:11
-
-
Save neilk/2c69743b22f84605e3d255056ee56c09 to your computer and use it in GitHub Desktop.
Retry logic for promises
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
/** | |
* 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