Retry Until Predicate
MediumPromises & Async15 min5 tests
Implement retryUntil(fn, predicate, maxAttempts, delay) that keeps calling fn until the predicate is satisfied or attempts are exhausted.
Requirements
- Call
fn()and check the result againstpredicate(result). - If the predicate returns
true, resolve with the result. - If
maxAttemptsis exceeded, reject with"Max attempts reached". - Wait
delayms between each attempt. - If
fnthrows, count it as a failed attempt and continue retrying.
Example
let count = 0;
const result = await retryUntil(
() => ++count,
(n) => n >= 3,
5,
10
);
// result === 3Hints (5)
- Use a for loop up to maxAttempts.
- Wrap the fn() call in try/catch to handle throwing functions.
- After each call, test the result with predicate(result).
- If the predicate passes, return the result immediately.
- After all attempts, throw "Max attempts reached".
Topics
- Promises & Async
Asked at
Netflix · Cloudflare · Stripe · Uber
