Skip to content

Instantly share code, notes, and snippets.

@bcomnes
Created January 23, 2019 17:36
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 bcomnes/e82127e8a87fc2303cf224f16eb008c3 to your computer and use it in GitHub Desktop.
Save bcomnes/e82127e8a87fc2303cf224f16eb008c3 to your computer and use it in GitHub Desktop.
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