Skip to content

Instantly share code, notes, and snippets.

@lambduli
Last active March 24, 2024 14:41
Show Gist options
  • Save lambduli/a9a2a0d7401921177a09f843c78c5063 to your computer and use it in GitHub Desktop.
Save lambduli/a9a2a0d7401921177a09f843c78c5063 to your computer and use it in GitHub Desktop.
Just a little POC of retry function.

Retry

A little POC of a retry function in JavaScript.

const retry = require('./retry')
function failNTimes(n) {
let failed = 0
return () => {
if (failed < n) {
++failed
throw new Error('failed')
}
return 'succeed'
}
}
const singleFail = failNTimes(1)
retry(singleFail, 2)
.then(res => console.assert(res === 'succeed'))
.then(() => console.log('It should succeed after second attempt'))
const fail3Times = failNTimes(3)
retry(fail3Times, 3)
.catch(err => console.assert(err.toString() === new Error('failed').toString()))
.then(() => console.log('It should fail after third attempt'))
let invoked = false
retry(() => (invoked = true), 0)
.then(() => console.assert(invoked === false))
.then(console.log('It should not have been invoked'))
// let n = 0
// const r = retry(() => {
// if (n < 3) {
// n++
// throw 'Error ' + n
// }
// return 'Success'
// }, 4)
// .then(res => console.log('res', res, n))
// .catch(() => console.log('catch', n))
module.exports = retry
function retry(fn, times, ...args) {
if (times === 0) {
return Promise.resolve()
}
return new Promise(resolve => {
resolve(fn(...args))
}).catch(err => {
if (times > 1) {
return retry(fn, times - 1, ...args)
}
return Promise.reject(err)
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment