Retry a flaky async call
advanced Promises Challenge 14 of 18
Write retry(fn, attempts, delayMs = 0). fn is an async function that sometimes fails, such as an API call to create test data in a slow environment.
Requirements
- Call
fnup toattemptstimes in total, and resolve with the first successful result. - Do not call
fnagain after it succeeds. - If every attempt fails, reject with the error from the last attempt.
- Treat a synchronous
throwfromfnthe same as a rejected Promise. - Wait
delayMsmilliseconds between attempts (not after the last one). - Reject when
attemptsis not a positive integer.
Expected output
await retry(makeFlaky(2), 3) → 'ok' (fails twice, succeeds on the 3rd call) await retry(makeFlaky(5), 3) → rejects with the 3rd failure's error
Test cases (7)
- ○succeeds after transient failures
- ○rejects with the last error when every attempt fails
- ○calls fn exactly attempts times on failure
- ○stops calling fn after the first success
- ○handles functions that throw synchronously
- ○waits delayMs between attempts
- ○rejects when attempts is less than 1
solution.jsExecutes in your browser
Ctrl/⌘ + Enter to run tests · your code is saved in this browser
Results
Run the tests to see results here.