Skip to content

Instantly share code, notes, and snippets.

@paulownia
Created September 20, 2019 04:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save paulownia/5834f6ae6c2c03a83e2db6bb0b63cee6 to your computer and use it in GitHub Desktop.
Save paulownia/5834f6ae6c2c03a83e2db6bb0b63cee6 to your computer and use it in GitHub Desktop.
retry sample
/*eslint no-console: 0 */
const retryDelay = 100;
const retryCount = 10;
function execute() {
return new Promise((resolve, reject) => {
setTimeout(() => {
const x = Math.random();
if (x > 0.8) {
resolve(x);
} else {
reject(x);
}
}, 100);
});
}
function delay(asyncFunc, time, count) {
console.log(`retry ${count}`);
return new Promise((resolve, reject) => {
setTimeout(() => {
asyncFunc().then((x) => {
console.log(`success: ${x}`);
resolve(x);
}).catch((x) => {
console.log(`failure: ${x}`);
reject(x);
});
}, time);
});
}
let p = execute();
let t = retryDelay;
for (let i = 0; i < retryCount; i++) {
p = p.catch(delay.bind(null, execute, t, i + 1));
t *= 2;
}
p.then((a) => {
console.log('ok:' + a);
}).catch((a) => {
console.log('ng:' + a);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment