@petitcode/eb-retry
v1.3.6
Published
Retry an async function with exponential backoff and jitter
Maintainers
Readme
@petitcode/eb-retry
Retry an async function with exponential backoff and jitter. Wraps node-retry with a Promise-friendly surface.
Install
npm i @petitcode/eb-retryUsage
const retry = require('@petitcode/eb-retry');
const data = await retry(
async (bail, attempt) => {
const res = await fetch('https://api.example.com/things');
if (res.status === 401) {
// hopeless — stop retrying
bail(new Error('Unauthorized'));
return;
}
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return res.json();
},
{ retries: 5 }
);API
retry(fn: (bail: (err: Error) => void, attempt: number) => any, opts?: RetryOptions): Promise<any>The supplied function can be sync or async. It receives:
bail(err)— abort retrying immediately (rejects the outer promise witherr).attempt— 1-based attempt counter. First call is1.
Options
All options are forwarded to node-retry:
| Option | Default | Meaning |
|---|---|---|
| retries | 10 | Maximum number of additional attempts after the first failure. |
| factor | 2 | Exponential factor — wait grows by this multiplier between attempts. |
| minTimeout | 1000 ms | Initial delay before the first retry. |
| maxTimeout | Infinity | Cap on the delay between attempts. |
| randomize | true | Apply jitter — multiply each delay by a random factor in [1, 2). |
| onRetry | — | Callback (err, attempt) fired after a failed attempt, before the wait. |
Bail
Calling bail(err) inside fn short-circuits retries — useful for permanent errors (auth, 404, malformed input):
await retry(async (bail) => {
const res = await fetch(url);
if (res.status === 401) {
bail(new Error('auth'));
return;
}
return res.json();
});Counting attempts
await retry(async (_bail, attempt) => {
log(`try ${attempt}`);
return doIt();
}, { retries: 3, onRetry: (err) => log(`retry: ${err.message}`) });License
MIT.
