retry
Retries the given function a specified number of times with a delay between each retry.
1. Code
/**
* Retries the given function a specified number of times with a delay between each retry.
* @param fn The function to retry.
* @param retries The number of times to retry the function. Default is 3.
* @param delay The delay in milliseconds between each retry. Default is 1000ms (1 second).
* @returns A Promise that resolves to the result of the function if it succeeds, or rejects with the last error if all retries fail.
*/
const retry = async <T>(
fn: Function,
retries: number = 3,
delay: number = 1000
): Promise<T> => {
try {
return await fn();
} catch (error) {
if (retries > 0) {
await new Promise((resolve) => setTimeout(resolve, delay));
return retry(fn, retries - 1, delay);
}
throw error;
}
};
export default retry;
2. Installation
npx @jrtilak/lazykit@latest add retry -ts
3. Description
The retry function retries the given function a specified number of times with a delay between each retry. If the function succeeds within the specified number of retries, the Promise will resolve with the result of the function. If the function fails on all retries, the Promise will be rejected with the last error. The retry function is designed to handle both synchronous and asynchronous functions, as it wraps the call to fn with Promise.resolve. This ensures that fn is always treated as a Promise, allowing the use of .then and .catch to handle the result or any errors.
The function retries the given function a specified number of times. The total number of times a function is called is retries + 1.
4. Props
Prop
Type
Default Value
5. Examples
import retry from ".";
const fn = async () => {
throw new Error("failed");
};
retry(fn, 2, 1000).catch((error) => {
console.log(error.message);
});
// Expected output: "failed" after retrying twice but It will call the function 3 times.