Skip to content

Instantly share code, notes, and snippets.

@scottwrobinson
Created November 16, 2023 22:33
Show Gist options
  • 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;
};
@scottwrobinson
Copy link
Author

scottwrobinson commented Sep 7, 2024

@vitaly-t How is it more generic? You don't have a way to validate errors and defaulting to infinite retries is questionable 😉

@vitaly-t
Copy link

vitaly-t commented Sep 7, 2024

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