Function autoRetry
Source: AutoRetry.ts
Automatically retries a failing async function up to a configurable number of times. Between attempts, an optional beforeRetry callback is invoked — use it for delay, logging, or early-exit logic. When all retries are exhausted, the last error is re-thrown.
Import
ts
import { autoRetry } from '@litert/utils-async';Signature
ts
async function autoRetry<TResult>(opts: IRetryOptions<TResult>): Promise<TResult>;Parameters
Parameter
opts: IRetryOptions<TResult>See
IRetryOptions.
Return Value
The result of the first successful invocation of opts.function.
Error Handling
TypeError— Thrown synchronously ifopts.maxRetriesis not a positive integer.AbortedError/ abort +Error— If the signal fires duringbeforeRetryand thebeforeRetryre-throws anAbortError, the last error from the main function is re-thrown.- Any error from
opts.beforeRetry(non-abort) — Propagated immediately, stopping the retry loop. - Last error from
opts.function— Re-thrown when all retries are exhausted.
Examples
Basic retry
ts
import { autoRetry } from '@litert/utils-async';
const result = await autoRetry({
maxRetries: 5,
function: async (ctx) => {
if (ctx.retriedTimes > 0) {
console.log(`Retry #${ctx.retriedTimes}`);
}
return await fetchData();
},
});Custom delay with abort support
ts
import { autoRetry, sleep, createExponentialBackoffDelayGenerator, compositeRetryDelayGenerator, fullJitter } from '@litert/utils-async';
const ac = new AbortController();
const genDelay = compositeRetryDelayGenerator({
delayGenerator: createExponentialBackoffDelayGenerator(500, 2),
jitter: fullJitter,
maxDelay: 10000,
});
const result = await autoRetry({
maxRetries: 10,
signal: ac.signal,
function: async () => fetchData(),
beforeRetry: async (ctx) => {
console.log(`Retry #${ctx.retriedTimes + 1}, last error: ${ctx.error}`);
await sleep(genDelay(ctx.retriedTimes), ctx.signal);
},
});