Fetch Every Page with an Async Generator
Write the code, see it run, pass the checks.
The problem
- medium
- Code
An API returns a list one page at a time. You're given fetchPage(cursor), which returns a promise of { items, next }: an array of items and the cursor for the next page, or null on the last page. Write paginate(fetchPage) as an async generator function, for use with for await...of. It fetches the first page with a cursor of null, yields its items one at a time, then fetches the page its next cursor points to, and so on until next is null. Pages may be empty. Fetch a page only when the loop asks for an item from it: nothing is fetched before the first item is asked for, and a loop that breaks while still in the first page never fetches the second. If fetchPage rejects, the loop throws that same error, after the items that came before it.
Your code must pass
- Yields every item from every page, in order
- Passes each page's cursor to the next fetch
- Skips empty pages
- Fetches a page only when it's needed
- Passes errors from fetchPage on