Typed Async Retry Helper

A generic retry helper that preserves the resolved value type, caps attempts, and backs off between failures without losing type information.

TypescriptResilience

Code

typescriptsnippet
25 lines
export interface RetryOptions {
  attempts: number;
  delayMs: number;
  isRetryable?: (error: unknown) => boolean;
}

export async function retryAsync<T>(
  task: () => Promise<T>,
  options: RetryOptions,
): Promise<T> {
  const shouldRetry = options.isRetryable ?? (() => true);
  let attempt = 0;
  let lastError: unknown;
  while (attempt < options.attempts) {
    attempt++;
    try {
      return await task();
    } catch (error) {
      lastError = error;
      if (attempt >= options.attempts || !shouldRetry(error)) break;
      await new Promise<void>((resolve) => setTimeout(resolve, options.delayMs * attempt));
    }
  }
  throw lastError;
}

How the snippet works

The working surface is the function retryAsync — everything else is wiring.

while (attempt < options.attempts) is the loop that carries the per-item work. Asynchronous boundaries use await, so failures surface as rejected promises at the call site instead of being swallowed.

Applying it

Import retryAsync from the file and call it — the rest of the code is implementation detail.

Statements that matter

await new Promise<void>((resolve) => setTimeout(resolve, options.delayMs * attempt));
const shouldRetry = options.isRetryable ?? (() => true);
return await task();

Interactive Tools for This Topic

FAQ

Which packages does this snippet need?
None. Every symbol the code uses resolves inside the standard library. The file defines `retryAsync` at load time.