Skip to content
SDETRole
SDETRole

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 fn up to attempts times in total, and resolve with the first successful result.
  • Do not call fn again after it succeeds.
  • If every attempt fails, reject with the error from the last attempt.
  • Treat a synchronous throw from fn the same as a rejected Promise.
  • Wait delayMs milliseconds between attempts (not after the last one).
  • Reject when attempts is 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.

Type to search across SDETRole.

Full-text search by Pagefind · runs in your browser Open search page →