Problem
Network calls fail for brief moments — a timeout, a blip, a temporary overload. Instead of failing on the first error, build a helper that calls the operation again after a pause, and makes each pause longer than the last so you do not hammer a struggling server.
Implement retry(fn, retries, delay) where:
fnis a function returning a promise (the operation to attempt).- On rejection, wait
delayms and try again, doubling the delay each time. - Give up after
retriesadditional attempts and reject with the last error. - Resolve as soon as any attempt succeeds.
Note: the total number of calls is retries + 1 (the initial try plus the extra attempts).
Input
let tries = 0;
const flaky = () =>
new Promise((res, rej) => (++tries < 3 ? rej("fail " + tries) : res("ok")));
retry(flaky, 5, 100).then(console.log); // succeeds on the 3rd attempt
Expected output
- Resolves with
"ok"after 3 attempts.
Implement from scratch:
function retry(fn, retries = 3, delay = 500) {
// Your code here
}