Created
November 16, 2023 22:33
-
-
Save scottwrobinson/692a31e0fdf648e537c232a62f8fdde4 to your computer and use it in GitHub Desktop.
Retry logic for any async function. Specify error validation, number of retries, delay, etc.
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 delay = ms => { | |
return new Promise(fulfill => { | |
setTimeout(fulfill, ms); | |
}); | |
}; | |
const callWithRetry = async (fn, {validate, retries=3, delay: delayMs=2000, logger}={}) => { | |
let res = null; | |
let err = null; | |
for (let i = 0; i < retries; i++) { | |
try { | |
res = await fn(); | |
break; | |
} catch (e) { | |
err = e; | |
if (!validate || validate(e)) { | |
if (logger) logger.error(`Error calling fn: ${e.message} (retry ${i + 1} of ${retries})`); | |
if (i < retries - 1) await delay(delayMs); | |
} | |
} | |
} | |
if (err) throw err; | |
return res; | |
}; |
@vitaly-t How is it more generic? You don't have a way to validate errors and defaulting to infinite retries is questionable 😉
It is more generic because:
- It supports callbacks for
retry
- It monitors and reports duration for the operation
- It maintains unified status for all callbacks
- It supports general-purpose error notifications (not something internal and specific above)
In your code you even not verifying delayMs
to determine when it is to be skipped. setTimeout(0)
is much slower than not using one.
etc.
defaulting to infinite retries is questionable
I'd argue the opposite. Use of some random number for that would be questionable.
Here's the original TypeScript version that explains the function better.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
More generic one - https://github.com/vitaly-t/retry-async/blob/main/src/retry-async.js