API reference / @evolu/common / Task / retry

Function: retry()

function retry<T, E>(__namedParameters, task): Task<T, E | RetryError<E>>;

Defined in: packages/common/src/Task.ts:484

Adds retry logic with exponential backoff and jitter to a Task.

Example

interface FetchError {
  readonly type: "FetchError";
  readonly error: unknown;
}

// Task version of fetch with proper error handling and cancellation support.
const fetch = (url: string) =>
  toTask((context) =>
    tryAsync(
      () => globalThis.fetch(url, { signal: context?.signal ?? null }),
      (error): FetchError => ({ type: "FetchError", error }),
    ),
  );

// `satisfies` shows the expected type signature.
fetch satisfies (url: string) => Task<Response, FetchError>;

const fetchWithRetry = (url: string) =>
  retry({ retries: PositiveInt.orThrow(3) }, fetch(url));

const result1 = await fetchWithRetry("https://api.example.com/data")();
result1 satisfies Result<Response, FetchError | RetryError<FetchError>>;

// With AbortController
const controller = new AbortController();
const result2 = await fetchWithRetry("https://api.example.com/data")(
  controller,
);
result2 satisfies Result<
  Response,
  FetchError | RetryError<FetchError> | AbortError
>;

Type Parameters

Type Parameter
T
E

Parameters

ParameterType
__namedParametersRetryOptions<E>
taskTask<T, E>

Returns

Task<T, | E | RetryError<E>>

Was this page helpful?