Skip to main content

retry

A function that retries a Promise-returning function until it succeeds.

You can configure the number of retries and the interval between retries. You can pass an AbortSignal to cancel the retry operation.


Code

🔗 View source code


Interface

typescript
function retry<T>(func: () => Promise<T>): Promise<T>;
function retry<T>(func: () => Promise<T>, count: number): Promise<T>;
function retry<T>(func: () => Promise<T>, options: RetryOptions): Promise<T>;

Usage

Basic Usage

typescript
import { retry } from '@modern-kit/utils';

// Retries fetchData up to 5 times until it succeeds.
const data = await retry(fetchData, 5);

Using Options

typescript
import { retry } from '@modern-kit/utils';

// Retries fetchData up to 5 times with a 1-second interval on failure.
const data = await retry(fetchData, { count: 5, delay: 1000 });

Using AbortSignal

typescript
import { retry } from '@modern-kit/utils';

const controller = new AbortController();

// The retry operation is cancelled when controller.abort() is called.
const data = await retry(fetchData, { count: 5, signal: controller.signal });