Skip to content
Exercise · Asynchronous code · lesson 9 of 12

Exercise: retry an async task

Write a function async function retry(fn, times). It calls fn() — a function with no arguments that returns a promise — and returns that promise's value. If the promise is rejected, retry calls fn() again, at most times calls in all. If every call is rejected, the promise from retry is rejected with the error of the last call.

In the tests, flaky(n, value).fn is such a function: its first n calls are rejected with the errors fail 1, fail 2 and so on, and the calls after them are fulfilled with value.

  • retry(flaky(0, "ok").fn, 3) → "ok"
  • retry(flaky(2, "late").fn, 3) → "late"
  • retry(flaky(3, "never").fn, 3) → rejected with the error fail 3

Constraints: times is an integer from 1 to 5; after the first successful call, fn is not called again.

Do not add extra imports unless the task says so explicitly.

retry.js — javascript
javascript · 4 lines
Ctrl+Enter run · Esc leave editor

Subscribe to take the course

The course is free. Sign in with Telegram and subscribe to the channel to open every lesson.

Sign in another way