Skip to content

Instantly share code, notes, and snippets.

@scottwrobinson
Created November 16, 2023 22:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save scottwrobinson/692a31e0fdf648e537c232a62f8fdde4 to your computer and use it in GitHub Desktop.
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.
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