Created
February 17, 2014 18:40
-
-
Save delapuente/9056419 to your computer and use it in GitHub Desktop.
Promise retry function with 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 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