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 against predicate(result).
  • If the predicate returns true, resolve with the result.
  • If maxAttempts is exceeded, reject with "Max attempts reached".
  • Wait delay ms between each attempt.
  • If fn throws, count it as a failed attempt and continue retrying.

Example

let count = 0;
const result = await retryUntil(
  () => ++count,
  (n) => n >= 3,
  5,
  10
);
// result === 3
Hints (5)
  1. Use a for loop up to maxAttempts.
  2. Wrap the fn() call in try/catch to handle throwing functions.
  3. After each call, test the result with predicate(result).
  4. If the predicate passes, return the result immediately.
  5. After all attempts, throw "Max attempts reached".

Topics

  • Promises & Async

Asked at

Netflix · Cloudflare · Stripe · Uber

Join Us
blur