Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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