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 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