Tweakr
    Preparing search index...

    Function retry

    • Retries an asynchronous operation a specified number of times with delay between attempts.

      This utility is useful for handling transient errors (e.g., network requests) by automatically retrying the provided async function on failure.

      Type Parameters

      • T

        The type of the resolved value from the async function.

      Parameters

      • fn: () => Promise<T>

        The asynchronous function to retry.

      • retries: number = 3

        Maximum number of retry attempts. Defaults to 3.

      • delay: number = 100

        Delay in milliseconds between retries. Defaults to 100.

      Returns Promise<T>

      A promise that resolves with the function’s result, or rejects after all retries fail.

      let attempt = 0;
      const result = await retry(async () => {
      if (attempt++ < 2) throw new Error("Failed");
      return "Success";
      }, 3, 200);

      console.log(result); // "Success"

      Will throw the last encountered error after exhausting all retries.

      1.1.0