Created
August 21, 2014 19:44
-
-
Save advait/7665d91c5d4b0e3cf632 to your computer and use it in GitHub Desktop.
Fibonacci backoff for promises. Retries a function indefinitely until it succeeds (Promise resolves).
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
/** | |
* Given a function promiseFunctionToRetry that returns a Promise, repeatedly | |
* call the function with a fibonacci backoff until it results in a resolved | |
* Promise. | |
* @param {function} promiseFunctionToRetry a function that returns a Promise | |
* that can potentially reject. This may be called multiple times. | |
* @param {number?} backoff An optional starting backoff in ms (default 1000) | |
* @return {Promise} guaranteed to never reject | |
*/ | |
var backoff = function(promiseFunctionToRetry, backoff) { | |
return new Promise(function(resolve) { | |
var currentBackoff = backoff || 1000; | |
var backoffStep = currentBackoff; | |
var retry = function() { | |
promiseFunctionToRetry() | |
.then(resolve, function() { | |
setTimeout(retry, currentBackoff); | |
var temp = currentBackoff; | |
currentBackoff += backoffStep; | |
backoffStep = temp; | |
}); | |
}; | |
retry(); | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment