Last active
September 5, 2016 12:10
-
-
Save dgoguerra/8ac0c4293595e87567957befad4a786a to your computer and use it in GitHub Desktop.
retry an async action until it doesn't fail
This file contains hidden or 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
| // 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(); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
usage example: