Retry a failing call
A JavaScript exercise from Scriptdrill. Solve it with a code editor in your browser that runs your function against example and hidden tests, and it is checked the moment you submit.
The task
Call `fn()` until it succeeds, at most `attempts` times, and resolve with its result. `fn` may return a Promise or a plain value, and it may throw or reject. If every attempt fails, reject with the error from the last attempt.
What this exercise teaches
await inside try catches both a rejected Promise and an error thrown synchronously by fn. Returning inside the loop stops at the first success, and the error kept from the final attempt is the one thrown.
A hint if you get stuck
An `async` function with a `for` loop and `try { return await fn(); } catch (e) { last = e; }` covers sync throws and rejections alike. Throw `last` after the loop.
This exercise is part of Pro
Pro unlocks all 45 exercises, with worked solutions and progress saved to your account. The free exercises work without an account.
You create a free account first, so Pro is attached to it.
Monthly is charged today and then every month until you cancel, in one click from your account page. Lifetime is one payment with no renewals. Full refund within 14 days of paying.