Implement retryWithBackoff(fn, { retries, baseDelay }). fn takes no arguments and returns a promise.
- Call
fnright away. If it resolves, resolve with its value. - If it rejects, wait and try again, up to
retriesmore times. Sofnruns at mostretries + 1times. - The wait before retry number k is
baseDelay * 2^(k - 1)ms, counting k from 1. WithbaseDelay = 100, the waits are 100, 200, 400, … - If every attempt fails, reject with the last error.
- A synchronous throw from
fncounts as a failed attempt. That meansfnthrows right away instead of returning a promise. retriesis 0 or more. With 0, there is one attempt and no waiting.
Input: retryWithBackoff(fetchUser, { retries: 3, baseDelay: 100 })
// fetchUser fails twice, then returns 'Ada'
Output: attempts at 0, 100 and 300 ms; resolves 'Ada'
Input: retryWithBackoff(alwaysFails, { retries: 2, baseDelay: 50 })
Output: attempts at 0, 50 and 150 ms; rejects with the third error