Skip to content

Instantly share code, notes, and snippets.

@YuMS
Created January 27, 2016 09:18
Show Gist options
  • Save YuMS/ffcaf6f53bed03137ecc to your computer and use it in GitHub Desktop.
Save YuMS/ffcaf6f53bed03137ecc to your computer and use it in GitHub Desktop.
generate a promise that keep invoking another promise generator until it succeed
function retryUntilSuccess(promiseFunc, args, timeout = 1000, retry = -1) {
return new Promise((resolve, reject) => {
const tryForTimes = (attempts) => {
promiseFunc(...args).then((result) => {
resolve(result);
}).catch((err) => {
if (attempts === 0) {
reject(err);
} else {
setTimeout(() => tryForTimes(attempts - 1), timeout);
}
});
};
tryForTimes(retry);
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment