Function: retry()

retry<T>(fn, options?): Promise<T>

Re-runs an async operation until it succeeds or the retry budget is exhausted. Synchronous functions work too — the call is wrapped in a promise internally.

Only failures that pass shouldRetry are retried; the final failure rethrows the last error thrown by the operation.

Type Parameters

T

T

Parameters

fn

() => T | Promise<T>

The operation to run. May be sync or return a promise.

options?

RetryOptions

Retry behaviour — see RetryOptions.

Returns

Promise<T>

A Promise resolving with the operation's value.

Example

// Retry a flaky request up to 3 times
const user = await retry(() => fetchUser(id), { retries: 3 })

// Only retry server errors, log every attempt
const data = await retry(() => api.post(payload), {
  retries: 5,
  backoff: 'exponential',
  shouldRetry: (err) => err instanceof HttpError && err.status >= 500,
  onRetry: (err, attempt, nextDelay) =>
    console.warn(`attempt ${attempt} failed, retrying in ${nextDelay}ms`)
})