JS Machine Coding Questions — Implementations You Must Know
Retry promise
- Run an async function (or promise factory); on failure, retry up to n times with optional delay between attempts.
- Loop runs retries + 1 total attempts (initial try plus retries retries).
- Exponential backoff (common follow-up): multiply delay by 2 ** attempt inside the loop.
1async function retryPromise(fn, { retries = 3, delayMs = 0 } = {}) {
2 let lastError;
3 for (let attempt = 0; attempt <= retries; attempt++) {
4 try {
5 return await fn();
6 } catch (err) {
7 lastError = err;
8 if (attempt === retries) throw err;
9 if (delayMs > 0) {
10 await new Promise((r) => setTimeout(r, delayMs));
11 }
12 }
13 }
14 throw lastError;
15}
16
17// Usage
18await retryPromise(
19 () => fetch("/api").then((r) => r.json()),
20 { retries: 2, delayMs: 200 }
21);