Shared Runner
A shared runner via runRetryPolicy with attempt-aware callbacks and custom sleep injection.
runRetryPolicy(policy, execute, options?) is a shared runner with attempt-aware callbacks and custom sleep injection. Every RetryPolicy — built-in or custom — runs through this same function. It calls execute once per attempt, consults the policy after each failure, sleeps, and stops on success, exhaustion, or abort.
Basic Usage
Pass a policy and an async function; the runner resolves with the function’s first successful return value.
import { exponentialBackoff, runRetryPolicy } from "@zap-studio/retry";
const policy = exponentialBackoff({
maxAttempts: 5,
baseDelayMs: 100,
maxDelayMs: 2_000,
});
const value = await runRetryPolicy(policy, async () => {
return await doWork();
});
Attempt Awareness
The execute callback receives the one-based attempt number, useful for logging or per-attempt behavior.
const value = await runRetryPolicy(policy, async (attempt) => {
console.log("Attempt:", attempt);
return await doWork();
});
Custom Sleep
By default, delays use defaultSleep (a setTimeout-based helper exported from retry). Inject your own sleep for deterministic tests or custom timing.
const value = await runRetryPolicy(
policy,
async () => {
return await doWork();
},
{
sleep: async (_delayMs) => {
// no delay in tests
},
},
);
See Non-throw Mode for throwOnExhausted: false, and Structured Errors for what runRetryPolicy(...) throws by default.
Run Options
All options are optional.
| Option | Type | Default | Description |
|---|---|---|---|
sleep |
(delayMs: number) => Promise<void> |
defaultSleep |
Delay function used between retry attempts. |
signal |
AbortSignal |
— | Cancels retry orchestration when aborted. See Abort Signal. |
throwOnExhausted |
boolean |
true |
true throws on exhaustion; false returns a RetryRunResult<T> union. |