Poll until a condition holds
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 }intervaldefaults to50ms between attempts,timeoutdefaults to2000ms 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 === 3Keeps 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
checkonce immediately, before any waiting. - Resolve with the first truthy result, exactly as returned.
- Await results, so an async
checkworks. - Wait
intervalmilliseconds between attempts. - Reject with an
Errorwhose message isPolling timed outoncetimeouthas elapsed.
Notes
- Call
checkonce 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
checkcan't quietly push you past the deadline.
Stuck? The javascript course covers everything this challenge needs.
- 1.resolves on the first check when it is already truthy
- 2.keeps polling until the check turns truthy
- 3.awaits an async check and returns its value unchanged
- 4.rejects once the timeout has elapsed
- 5.waits between attempts rather than spinning
These assertions run in your browser the moment you hit Run. Pass all of them to claim the XP.
Discussion
Sign in to postNo comments yet. Be the first to say something.