Created
April 7, 2016 17:39
-
-
Save xhjkl/5400188b2bfcece145fa8bc998e241c6 to your computer and use it in GitHub Desktop.
Promise again if could not fulfil for the first time
This file contains hidden or 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
// Promise to run an operation multiple times | |
// until first success or until exhaustion of attempts | |
// | |
// In case of failure, the enclosing promise | |
// is rejected using the last error. | |
// | |
// Supplied operation could be a promise. | |
// | |
// times -- how many times to try, | |
// 1 means try once and do not retry, | |
// 0 means do not run anything at all | |
// fn -- what to run | |
// | |
const retry = (times, fn) => { | |
if (times < 1) { | |
return Promise.reject('attempts exhausted'); | |
} | |
return Promise | |
.resolve(times) | |
.then(fn) | |
.catch(() => retry(times - 1, fn)); | |
}; | |
module.exports = retry; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment