Skip to content

Instantly share code, notes, and snippets.

@delapuente
Created February 17, 2014 18:40
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/9056419 to your computer and use it in GitHub Desktop.
Save delapuente/9056419 to your computer and use it in GitHub Desktop.
Promise retry function with thenable interface
function retry(target, keepTrying) {
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:
retry(something, function(e, n) { return n<5; }).then(progress, error)
function retry(target, keepTrying) -> promise:
It takes a target function returning a promise and a test function and keep 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