Skip to content

retry

type: function
since: v2.5.0

The retry function repeatedly calls a function until it returns a value other than undefined, retries are exhausted, or timeout is reached.

The retryErrorScope app error scope array is exported by this utility and can be used to filter thrown AppError by scope for this specific utility.
To learn more about error handling please refer to error handling section of the getting started guide, and the AppError documentation.

Usage

import { retry } from '@mustib/utils';
await retry(async () => {
const ok = Math.random() > 0.7;
return ok ? 'done' : undefined;
});
await retry({ retries: 5, interval: 100, timeout: 1000 }, async () => {
const response = await fetch('/some-endpoint');
return response.ok ? response.json() : undefined;
});

Definition

function retry<T extends () => any>(fn: T): Promise<ReturnType<T> | undefined>
function retry<T extends () => any>(
options: {
retries?: number;
interval?: number;
timeout?: number;
},
fn: T,
): Promise<ReturnType<T> | undefined>

Parameters

  1. optionsOrFn
    type optionsOrFn = Options | Function;
    • Either the callback function or an options object.
    • Options object fields:
      • retries
        • Maximum attempts.
        • default:
          timeout === undefined ? 3 : Infinity
      • interval
        • Delay in milliseconds between attempts.
        • default:
          0
      • timeout
        • Maximum total time in milliseconds.
        • default:
          undefined
  2. fn
    type fn = Function;
    • Callback to retry when `options` is provided as first argument.

Returns

type T = Promise<ReturnType<T> | undefined>;
  • First non-undefined callback value, or `undefined` if retry constraints are reached.

Notes

  • Errors thrown by the callback are not caught by retry; they reject as normal.
  • Invalid options throw an AppError scoped with retryErrorScope.