Retry a request with backoff
A request that fails once will often succeed on the next try. Exponential backoff — doubling the wait after each failure — gives the dependency room to recover without hammering it.
Implement retry(task, { attempts, baseDelay }). Call task() and resolve as soon as it does; on rejection, wait baseDelay and try again, doubling the delay between each subsequent attempt until attempts is exhausted.
Arguments
task() => Promise<T>- An async function to invoke. Called afresh on each attempt.
options.attemptsnumber- Maximum number of calls to
taskbefore giving up. Defaults to 3. options.baseDelaynumber- Milliseconds to wait after the first failure. Doubles after each subsequent failure. Defaults to 100.
Returns
Promise<T> — Resolves with the first successful value from task. Rejects with the last error if every attempt fails.
Examples
let calls = 0;
const value = await retry(async () => {
calls++;
if (calls < 3) throw new Error("flaky");
return "ok";
}, { attempts: 5, baseDelay: 10 });
// value === "ok", calls === 3Succeeds on the third attempt; earlier failures are swallowed.
try {
await retry(async () => { throw new Error("down"); }, { attempts: 2, baseDelay: 10 });
} catch (err) {
// err.message === "down" — the last error surfaces
}What it has to do
- Resolve as soon as any attempt succeeds.
- Reject with the last error once attempts are exhausted.
- Double the delay after each failure, starting at
baseDelay.
Notes
- Don't sleep after the final failed attempt — rejecting immediately feels snappier and matches what callers expect.
- In production you'd typically add jitter to the delay so retrying clients don't all pile back on at the same instant.
Stuck? The javascript course covers everything this challenge needs.
- 1.resolves on first attempt when it succeeds
- 2.retries until an attempt succeeds
- 3.rejects with last error when attempts exhausted
These assertions run in your browser the moment you hit Run. Pass all of them to claim the XP.
Discussion
Sign in to postNo comments yet. Be the first to say something.