Created
January 23, 2019 17:36
-
-
Save bcomnes/e82127e8a87fc2303cf224f16eb008c3 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
var pause = (duration) => new Promise(res => setTimeout(res, duration)); | |
var exponentialBackoff = (func, attempts = 1, delay = 50) => { | |
console.log('attempts', attempts) | |
return func().catch(err => { | |
console.log('error', err) | |
if (attempts > 1) { | |
console.log(`Retries left ${attempts - 1}`) | |
console.log(`Next delay ${delay * 2}`) | |
return pause(delay).then(() => exponentialBackoff(func, attempts - 1, delay * 2)) | |
} | |
return Promise.reject(err) | |
}) | |
} | |
function sometimesFails() { | |
var percentFail = 0.8; | |
var passed = Math.random() >= 0.8; | |
console.log('passed', passed) | |
if (passed) { | |
return Promise.resolve() | |
} | |
console.log('return reject') | |
return Promise.reject() | |
} | |
var maxAttempts = 10 | |
exponentialBackoff(sometimesFails, maxAttempts).then(() => { | |
console.log('success!') | |
}).catch((e) => { | |
console.log('never passed!') | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment