Retry a Failing Async Call

Write the code, see it run, pass the checks.

The problem

  • medium
  • Code
  • Pro

Write retry(fn, { attempts, delay }), where fn takes no arguments and returns a promise, and attempts is at least 1. Call fn straight away. If its promise resolves, resolve with that value. If it rejects and fewer than attempts calls have been made, wait, then call fn again: delay milliseconds before the second call, twice that before the third, four times before the fourth, and so on (exponential backoff). If the last allowed call also rejects, reject with its error, without waiting any longer. The checks use delays of 10 to 20 milliseconds.

Your code must pass

  • Resolves straight away when the first call works
  • Tries again until a call works
  • Rejects with the last error once attempts run out
  • Doubles the wait before each new call