cf.completefrontend

Write the codeMedium

Write retry(fn, { retries, delay }): call an async function again when it fails.

Call fn(attempt), with attempt starting at 1. If it fails, by throwing or by returning a promise that rejects, wait delay ms and try again with the next attempt.

retries is how many extra attempts are allowed after the first, so retries: 2 means at most three calls. Resolve with the first success; if every attempt fails, reject with the last error.

Write this
async function retry(fn, { retries = 3, delay = 0 } = {}) {
  // your code
}
 
// const flaky = async (attempt) => {
//   if (attempt < 3) throw new Error(`attempt ${attempt} failed`);
//   return "ok";
// };
// await retry(flaky, { retries: 2, delay: 100 }); // "ok": attempts 1 and 2 fail, attempt 3 works
// await retry(flaky, { retries: 1, delay: 100 }); // rejects with Error "attempt 2 failed": only two attempts allowed

The answer

Write it yourself first. Then compare it with a reference solution and the checks it passes.

Checking your sign-in…