All files / src/promises retry.ts

100% Statements 7/7
100% Branches 2/2
100% Functions 1/1
100% Lines 6/6

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21                2x   2x 5x 5x   4x   1x        
/**
 * Attempts a request {@link n} times until it resolves.
 *
 * @param fn The function to invoke.
 * @param n The maximum number of attempts
 * @returns A resolved promise if it succeeds or the rejected promise if it exceeds {@link n}
 */
export async function retry<T>(fn: () => Promise<T>, n: number): Promise<T> {
  let attempts = 0;
 
  while (true) {
    try {
      return await fn();
    } catch (error) {
      if (++attempts < n) continue;
 
      throw error;
    }
  }
}