Skip to content
  • Here's a slightly modified version, printing the function name in the error and adding typescript types:

    export async function retry<T>(
      fn: () => Promise<T>,
      retriesLeft: number = 3,
      interval: number = 1000,
      exponential: boolean = false
    ): Promise<T> {
      try {
        const val = await fn();
        return val;
      } catch (error) {
        if (retriesLeft) {
          await new Promise(r => setTimeout(r, interval));
          return retry(
            fn,
            retriesLeft - 1,
            exponential ? interval * 2 : interval,
            exponential
          );
        } else throw new Error(`Max retries reached for function ${fn.name}`);
      }
    }
  • If fn() needs arguments, how to change the above code to make it work? thx

  • You could wrap your function in another function together with the arguments:

    retry(() => fn(arg1, arg2))
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment