Created
October 22, 2024 09:12
-
-
Save Kmaschta/3edc0fa2b7694755ec48836b77207770 to your computer and use it in GitHub Desktop.
Retry function in TypeScript
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
type Options = { | |
maxRetries?: number; // Maximum amount of retries before raising the error (default: 3) | |
silent?: boolean; // Minimize the error as warning when retrying the function (default: true) | |
wait?: number; // Wait time before each retry in milliseconds (default: 500ms) | |
exponentialBackoff?: boolean; // Wait longer every time we retry (default: false) | |
randomize?: boolean; // Wait a random amount of time before retrying, maximum double of the given time (default: null) | |
}; | |
const waitMs = (ms: number) => new Promise(resolve => setTimeout(resolve, ms)); | |
const getRandomInt = (max: number) => Math.floor(Math.random() * max); | |
const retry = async (fn, opts?: Options, i: number = 1) => { | |
const maxRetries = opts?.maxRetries ?? 3; | |
const silent = opts?.silent ?? true; | |
const wait = opts?.wait ?? 500; | |
const exponentialBackoff = opts?.exponentialBackoff ?? false; | |
const randomize = opts?.randomize ?? false; | |
try { | |
// await is important here | |
return await fn(); | |
} catch (error) { | |
if (i > maxRetries) { | |
throw error; | |
} | |
console.warn( | |
`(${i}/${maxRetries}) Retrying function "${fn.name}" due to the following error`, | |
); | |
if (!silent) { | |
console.warn(error.stack); | |
} | |
if (wait) { | |
await waitMs( | |
exponentialBackoff | |
? wait * i | |
: randomize | |
? wait / 2 + getRandomInt(wait) | |
: wait, | |
); | |
} | |
return await retry(fn, opts, i + 1); | |
} | |
}; | |
export default retry; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment