Retry Operation Wrapper With Error Filters
Wrap flaky operations with the retry package using predicate-based retries, exponential factors, randomization, and per-operation abort signals.
Code
import retry from 'retry';
async function fetchWithRetry(url, { signal } = {}) {
const operation = retry.operation({
retries: 5,
factor: 2,
minTimeout: 500,
maxTimeout: 8000,
randomize: true,
});
return new Promise((resolve, reject) => {
operation.attempt(async (currentAttempt) => {
try {
const res = await fetch(url, { signal });
if (res.status >= 500) throw new Error('upstream ' + res.status);
resolve(await res.json());
} catch (err) {
if (operation.retry(err)) return;
reject(operation.mainError());
}
});
});
}
const data = await fetchWithRetry('https://api.example.com/pricing');
console.log('plans:', data.plans.length);Report a problem with this exampleOpens a pre-filled issue on GitHub.