Use a generator to paginate any API
Use a generator to paginate any API in JavaScript, hiding the page loop behind for await so callers see one stream of items. Works in Node.js 24.
Callers want items, not pages. An async generator can fetch page after page and yield the items one at a time, so the paging detail stays in one place.
const pages = [
{ items: ['a', 'b'], next: 1 },
{ items: ['c'], next: 2 },
{ items: ['d', 'e'], next: null },
];
const fetchPage = async (n) => pages[n];
async function* allItems() {
let cursor = 0;
while (cursor !== null) {
const page = await fetchPage(cursor);
yield* page.items;
cursor = page.next;
}
}
const out = [];
for await (const item of allItems()) out.push(item);
console.log(out);[ 'a', 'b', 'c', 'd', 'e' ]fetchPage stands in for a real request. yield* hands over every item of the page, then the loop follows the cursor until it is null. Nothing is fetched until the consumer asks for the next item, so a caller that stops with break stops the requests too. See async generators.
It fetches pages one after another. If the API allows it and order does not matter, prefetching the next page while the current one is consumed is faster, at the cost of a more complex loop.