Created
February 17, 2014 19:00
-
-
Save delapuente/9056776 to your computer and use it in GitHub Desktop.
Promise retry method for functions returning a thenable interface
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
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