Skip to content

Instantly share code, notes, and snippets.

@xhjkl
Created April 7, 2016 17:39
Show Gist options
  • Save xhjkl/5400188b2bfcece145fa8bc998e241c6 to your computer and use it in GitHub Desktop.
Save xhjkl/5400188b2bfcece145fa8bc998e241c6 to your computer and use it in GitHub Desktop.
Promise again if could not fulfil for the first time
// 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