goldies
    Preparing search index...

    Function retry

    • Calls a function until it succeeds, waiting longer between each attempt (exponential backoff).

      Type Parameters

      • T

      Parameters

      • fn: (attempt: number) => T | Promise<T>

        The work to retry. It gets the attempt number, starting at 1, and can return a value or a promise. An attempt fails when it throws or the promise rejects.

      • options: RetryOptions = {}

        How many attempts to make, how long to wait between them, and when to stop early.

      Returns Promise<T>

      The result of the first attempt that succeeds.

      The last attempt's error, once every attempt has failed or shouldRetry returns false. The signal's reason, if signal aborts. A RangeError, if attempts isn't a positive integer.

      const response = await retry(async () => {
      const res = await fetch(url);
      if (!res.ok) throw new Error(`HTTP ${res.status}`);
      return res;
      });
      // 5 attempts, 500ms apart, giving up after 10 seconds
      await retry(() => connect(), {
      attempts: 5,
      delay: 500,
      factor: 1,
      signal: AbortSignal.timeout(10_000),
      });