Deviopath › JavaScript

Retry an Async Task

Hard · Async

Write an async function retry(fn, attempts, delayMs) that calls fn until it succeeds, at most attempts times in total.

- fn may fail in two ways: by throwing right away, or by returning a Promise that rejects. Handle both.

- As soon as a call succeeds, resolve with its value and stop calling fn.

- Wait delayMs milliseconds between attempts (not after the last one).

- If every attempt fails, reject with the error from the last attempt.

testRetry(failTimes, attempts) is already written: it creates a task that fails failTimes times before succeeding and calls your retry with a 30ms delay. It reports the result (or error message), the number of calls, whether each pause between calls was long enough (waits) and whether you waited after the last call (waitedAfterLast).

Next: Build Your Own Promise.all