AniUI Academy

Poll until a condition holds

mediumAsync & Promises+250 XPPractice

Plenty of backends hand you a job id and expect you to check back: video encoding, report generation, payment confirmation. The client keeps asking until the status flips, and must stop asking eventually.

Implement pollUntil(check, options) where options may contain interval (default 50) and timeout (default 2000). Call check() immediately; it may return a value or a promise. If the awaited result is truthy, resolve with that exact value. Otherwise, if at least timeout milliseconds have elapsed since the first call, reject with new Error("Polling timed out"). Otherwise wait interval milliseconds and call check() again. check is never called again after the returned promise settles.

Arguments

check() => any | Promise<any>
The polling function. Returns a value or a promise; a truthy awaited result resolves the poll.
options{ interval?: number, timeout?: number }
interval defaults to 50ms between attempts, timeout defaults to 2000ms before giving up.

Returns

Promise<any> — A promise that resolves with the first truthy result. Rejects with Error("Polling timed out") once timeout has elapsed.

Examples

let calls = 0;
const value = await pollUntil(() => {
  calls++;
  return calls < 3 ? false : "done";
}, { interval: 10, timeout: 500 });
// value === "done", calls === 3

Keeps asking until the check returns something truthy.

try {
  await pollUntil(() => false, { interval: 10, timeout: 60 });
} catch (error) {
  // error.message === "Polling timed out"
}

Rejects with a sentinel error once the deadline passes.

What it has to do

  • Call check once immediately, before any waiting.
  • Resolve with the first truthy result, exactly as returned.
  • Await results, so an async check works.
  • Wait interval milliseconds between attempts.
  • Reject with an Error whose message is Polling timed out once timeout has elapsed.

Notes

  • Call check once immediately before any waiting — consumers usually want to see a cached-ready result without a delay.
  • Measure the timeout from the very first call so a slow check can't quietly push you past the deadline.

Stuck? The javascript course covers everything this challenge needs.

Try it yourself
Loading playground...
5 tests · +250 XP

Discussion

Sign in to post
Sign in to join the conversation.Sign in

No comments yet. Be the first to say something.