Skip to content

Instantly share code, notes, and snippets.

@oscarkuo
Last active April 21, 2016 02:08
Show Gist options
  • Save oscarkuo/6685cc9f4e8bb52f4ad274bd74924bd5 to your computer and use it in GitHub Desktop.
Save oscarkuo/6685cc9f4e8bb52f4ad274bd74924bd5 to your computer and use it in GitHub Desktop.
Promise retry
'use strict';
let i = 0;
const fn = () => {
if (i++ < 5)
throw new Error(`crap ${i}`);
return "success";
};
const pfn = (resolve, reject) => {
try {
resolve(fn());
} catch (ex) {
console.log(ex);
reject(ex);
}
};
const ppfn = () => {
return new Promise(pfn);
}
const retry = (retries, fn) => {
return fn().catch((e) => {
if (retries <= 0) {
throw e;
}
console.log('retry attempt ' + retries + ' left');
// return a promise from then(), the next then() will be on the returned promise
// http://stackoverflow.com/questions/27715275/whats-the-difference-between-returning-value-or-promise-resolve-from-then
return retry(retries - 1, fn);
});
};
retry(7, ppfn);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment