Skip to main content

@std/async@1.0.9
Built and signed on GitHub Actions

Utilities for asynchronous operations, like delays, debouncing, or pooling

This package works with Cloudflare Workers, Node.js, Deno, Bun, Browsers
This package works with Cloudflare Workers
This package works with Node.js
This package works with Deno
This package works with Bun
This package works with Browsers
JSR Score
100%
Published
2 weeks ago (1.0.9)
function retry
retry<T>(
fn: (() => Promise<T>) | (() => T),
options?: RetryOptions,
): Promise<T>

Calls the given (possibly asynchronous) function up to maxAttempts times. Retries as long as the given function throws. If the attempts are exhausted, throws a RetryError with cause set to the inner exception.

The backoff is calculated by multiplying minTimeout with multiplier to the power of the current attempt counter (starting at 0 up to maxAttempts - 1). It is capped at maxTimeout however. How long the actual delay is, depends on jitter.

When jitter is the default value of 1, waits between two attempts for a randomized amount between 0 and the backoff time. With the default options the maximal delay will be 15s = 1s + 2s + 4s + 8s. If all five attempts are exhausted the mean delay will be 9.5s = ½(4s + 15s).

When jitter is 0, waits the full backoff time.

Examples

Example configuration 1

import { retry } from "@std/async/retry";
const req = async () => {
 // some function that throws sometimes
};

// Below resolves to the first non-error result of `req`
const retryPromise = await retry(req, {
 multiplier: 2,
 maxTimeout: 60000,
 maxAttempts: 5,
 minTimeout: 100,
 jitter: 1,
});

Example configuration 2

import { retry } from "@std/async/retry";
const req = async () => {
 // some function that throws sometimes
};

// Make sure we wait at least 1 minute, but at most 2 minutes
const retryPromise = await retry(req, {
 multiplier: 2.34,
 maxTimeout: 80000,
 maxAttempts: 7,
 minTimeout: 1000,
 jitter: 0.5,
});

Type Parameters

The return type of the function to retry and returned promise.

Parameters

fn: (() => Promise<T>) | (() => T)

The function to retry.

optional
options: RetryOptions

Additional options.

Return Type

The promise that resolves with the value returned by the function to retry.

Add Package

deno add jsr:@std/async

Import symbol

import { retry } from "@std/async";

---- OR ----

Import directly with a jsr specifier

import { retry } from "jsr:@std/async";

Add Package

npx jsr add @std/async

Import symbol

import { retry } from "@std/async";

Add Package

yarn dlx jsr add @std/async

Import symbol

import { retry } from "@std/async";

Add Package

pnpm dlx jsr add @std/async

Import symbol

import { retry } from "@std/async";

Add Package

bunx jsr add @std/async

Import symbol

import { retry } from "@std/async";