retry
Retries the given function a specified number of times with a delay between each retry.
1./**2.* Retries the given function a specified number of times with a delay between each retry.3.**/4.const retry = async <T,>(5.fn: Function,6.retries: number = 3,7.delay: number = 1000,8.): Promise<T> => {9.try {10.return await fn();11.} catch (error) {12.if (retries > 0) {13.await new Promise((resolve) => setTimeout(resolve, delay));14.return retry(fn, retries - 1, delay);15.}16.throw error;17.}18.};19.20.export default retry;
1. Installtion
npx @jrtilak/lazykit add retry
2. Parameters
-
fn
(Function
)
The function to retry. This function should return a promise. -
retries
(optional) (number
)
The number of times to retry the function if it fails. Defaults to3
. -
delay
(optional) (number
)
The number of milliseconds to wait between retries. Defaults to1000
.
3. Returns
Promise<T>
Returns a promise that resolves to the value returned byfn
if it succeeds, or rejects with the last error if all retries fail.
4. Type Parameters
T
The return type of the functionfn
. This ensures that the returned promise has the correct type based on whatfn
returns.
5. Usage
1.import retry from "@/utils/retry";2.3.let count = 0;4.const fn = async () => {5.count++;6.console.log("Retry: ", count);7.if(count < 4){8.throw new Error("failed");9.}10.};11.12.retry(fn, 5, 1000)13..then(() => {14.console.log("success");15.})16..catch((error) => {17.console.log(error.message);18.});19.// Expected output: "failed" after retrying twice but It will call the function 3 times.