Skip to content

Instantly share code, notes, and snippets.

@voyagerwoo
Last active December 14, 2017 11:15
Show Gist options
  • Select an option

  • Save voyagerwoo/a6f5b664c38662a1ab0def21a50f27ec to your computer and use it in GitHub Desktop.

Select an option

Save voyagerwoo/a6f5b664c38662a1ab0def21a50f27ec to your computer and use it in GitHub Desktop.
RetryPromise.js
function retryPromise(promiseFunc, args, retryTimes) {
const max = retryTimes;
let result;
const retry = (promiseFunc, args, retryTimes) => new Promise((resolve, reject) => {
if (retryTimes <= 0) {
const message = `${promiseFunc.name} : ${max} times failed...`;
console.log(message);
reject(new Error(message)); return;
}
return promiseFunc.apply(null, args).then(r => {
console.log(`${promiseFunc.name} : ${max - retryTimes + 1} times success!`)
result = r;
return resolve(result)
}).catch(e => {
return retry(promiseFunc, args, --retryTimes).then(r => resolve(r))
}).catch(err => {
reject(err);
});
});
return retry(promiseFunc, args, retryTimes);
}
function test(param) {
return new Promise((resolve, reject) => {
console.log(param);
if (Math.random()*100 > 90)
resolve("test is succeed.")
else
reject("err");
});
}
retryPromise(test, ["keep going!!"], 10)
.then(r => console.log("success : ", r))
.catch(e => console.log("finally fail : ", e));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment