retry
Retries an async (or sync) function up to a specified number of attempts, with configurable delay and backoff strategy.
Import
Section titled “Import”import { retry } from "1o1-utils";import { retry } from "1o1-utils/retry";Signature
Section titled “Signature”async function retry<T>({ fn, attempts, delay, backoff, onRetry }: RetryParams<T>): Promise<T>Parameters
Section titled “Parameters”| Name | Type | Required | Description |
|---|---|---|---|
| fn | () => Promise<T> | T | Yes | The function to retry |
| attempts | number | No | Maximum number of attempts (positive integer, default: 3) |
| delay | number | No | Delay between retries in ms (default: 1000) |
| backoff | "fixed" | "exponential" | No | Backoff strategy (default: "fixed") |
| onRetry | (error, attempt) => void | No | Callback invoked on each retry |
Returns
Section titled “Returns”Promise<T> — The result of the first successful call.
Examples
Section titled “Examples”const data = await retry({ fn: () => fetch("/api/data").then((r) => r.json()), attempts: 5, delay: 2000, backoff: "exponential",});
// With retry callbackawait retry({ fn: fetchData, onRetry: (error, attempt) => { console.log(`Attempt ${attempt} failed:`, error); },});Edge Cases
Section titled “Edge Cases”- Throws if
fnis not a function. - Throws if
attemptsis not a positive integer. - Throws if
delayis negative orNaN. - Throws if
backoffis not"fixed"or"exponential". - With exponential backoff, delay is
delay * 2^ifor attempti. - Throws the last error after all attempts are exhausted.
Also known as
Section titled “Also known as”retry on failure, exponential backoff, resilient call, auto retry
Prompt suggestion
Section titled “Prompt suggestion”I'm using 1o1-utils (npm: https://www.npmjs.com/package/1o1-utils, GitHub: https://github.com/pedrotroccoli/1o1-utils, LLM context: https://pedrotroccoli.github.io/1o1-utils/llms.txt). Show me how to use retry with exponential backoff for a flaky API