retry

Retries the given function a specified number of times with a delay between each retry.

1. Code

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

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

function*Function---
retriesnumber3
delaynumber1000

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.