Created
September 20, 2019 04:18
-
-
Save paulownia/5834f6ae6c2c03a83e2db6bb0b63cee6 to your computer and use it in GitHub Desktop.
retry sample
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/*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