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; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
It is more generic because:
retry
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.
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.