Skip to content

Instantly share code, notes, and snippets.

@delapuente
Created February 17, 2014 19:00
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 delapuente/9056776 to your computer and use it in GitHub Desktop.
Save delapuente/9056776 to your computer and use it in GitHub Desktop.
Promise retry method for functions returning a thenable interface
Function.prototype.retryWhile = function(keepTrying) {
var target = this;
var retryCount = 1;
var fulfill, reject;
var promise = new Promise(function (f, r) {
fulfill = f;
reject = r;
});
realRetry();
return promise;
function realRetry() {
target().then(
function (result) { fulfill(result); },
function (error) { setTimeout(
function _doRetry() {
if (keepTrying(error, retryCount)) {
retryCount++;
realRetry();
} else {
reject(error);
}
}
); }
);
}
}
/*
How to use:
- Retry something().then(progress, error) 5 times:
something.retryWhile(function(e, n) { return n<5; }).then(progress, error)
target.retryWhile(keepTrying) -> promise:
Return a promise that is fulfilled when the promise returned by target is fulfilled. It keeps trying until test
function is false. Each retry, keepTrying function receives the reject value and the number of retry.
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment