Question presented to candidate: "Say you have a paginated REST API — each request returns a page of items plus a cursor for the next page, or null once there is no more data. Implement a class that lets a caller iterate over EVERY item across ALL pages with a plain for await...of loop, without the caller ever having to think about pages, cursors, or when to make the next network request. Does your implementation fetch every page up front, or only as needed?"
What a strong answer should cover:
Symbol.asyncIteratoris the async counterpart toSymbol.iterator— an object implementing it can be consumed withfor await...of, and the cleanest way to implement it on a class is as an ASYNC GENERATOR method (async *[Symbol.asyncIterator]() { ... }), not by hand-building an object with a.next()method that returns promises.- The generator's body does the real page-fetching work:
awaitthe current page,yieldeach of its items one at a time, then move to the next cursor and loop —for await...oftransparently awaits each yielded value on the consumer's behalf, though here the yielded values are already-resolved plain items, not promises. - A correct implementation is genuinely LAZY: it does not prefetch every page before the consumer starts iterating. The next page is only fetched once the CURRENT page's items have all been consumed and the loop asks for more.
- The loop terminates when the API signals no more data — typically a
null/undefinedcursor — which the generator detects by simply falling out of itsdo...while(or equivalent) loop, letting the generator return normally. - A strong answer distinguishes this from eagerly fetching ALL pages into one big array first: the async-generator approach lets the consumer start processing item 1 almost immediately, and lets them
breakout of the loop early (e.g., after finding what they needed) without ever fetching pages that turned out to be unnecessary. - Error handling: a rejected
fetchfor a given page should propagate out of thefor await...ofloop as a normal, catchable exception at the point where that page was needed, not silently stop iteration.
Clarifying questions expected:
- "Should the iterator retry a failed page fetch automatically, or is surfacing the error to the caller the expected behavior?" — a real, practical question about the actual API contract being wrapped.
- "Does the consumer need the ability to break out of the loop early without fetching remaining pages, or is fetching everything eventually acceptable?" — directly affects whether laziness is a hard requirement or a nice-to-have.
Code / implementation expected: Yes — a real, runnable implementation plus real, timestamped evidence that pages are genuinely fetched one at a time, lazily, in the correct order.