Skip to content
jshacks.dev
Functions

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.

1 min read
Summarize in AI

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.

JavaScript
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);
Text
[ '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.

Also inAPIs
Taggednode 24
Share

More snippets

APIs

Fetch JSON and handle HTTP errors

Fetch JSON in the browser or Node.js 24 and throw on 404 or 500 yourself, because fetch only rejects on network failure and does not check the status.

1 min read
Functions

Write a once function

Write a once function in JavaScript that runs a callback a single time and returns the cached result after that. Works in any Node.js, ES2015 or later.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.