A little POC of a retry
function in JavaScript.
Last active
March 24, 2024 14:41
-
-
Save lambduli/a9a2a0d7401921177a09f843c78c5063 to your computer and use it in GitHub Desktop.
Just a little POC of retry function.
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
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)) |
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
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