Skip to content

This notebook belongs to

Sadat Jubayer

Senior Software Engineer at Premio

If found, please return to hello@jubayer.dev

Vol. 7Seven years of building

Started
January 2020
Everyday tools
TypeScript, Vue, React, Next.js, NestJS, React Native
Education
B.Sc. CSSE, AIUB, 2020
2 min readJavaScript

Collect async iterables with Array.fromAsync

Collect an async generator into an array, map pages as they arrive, and keep a loop when you need partial results.

You have an async generator that yields one page of IDs at a time. The caller needs all the pages to build an export, so it opens an empty array, loops with for await...of, and pushes each page. Array.fromAsync handles that loop when collecting is the whole job.

Collect the pages

The generator below uses two arrays to stand in for two pages from an API. Save it as pages.mjs and run node pages.mjs with Node 22 or later.

async function* pages() {
  yield [101, 102]
  yield [103]
}

const allPages = await Array.fromAsync(pages())
console.log(JSON.stringify(allPages))

The output is [[101,102],[103]]. Each yielded array is one entry in the result. If your export needs a single list of IDs, call allPages.flat() after collection.

Start with await. The first value you get from calling Array.fromAsync is a promise. The result becomes available after the iterator finishes. Calling Array.from(pages()) in this example produces an empty array because the async generator supplies neither a synchronous iterator nor a length to read.

Let the generator control the pace

Array.fromAsync requests the next value and waits for it before asking again. If page two needs the cursor returned by page one, collect the pages from the generator that follows that cursor. Leave the request logic and the termination condition in the generator.

You can map each yielded value while collecting. The mapper receives the page and its index. For an export that needs one count per page, pass page => page.length as the second argument. The result for these pages is [2, 1]. If the mapper returns a promise, collection waits for it before moving on.

Keep the loop for partial work

The array arrives at the end, and a failed page rejects the promise. If a later request fails, the rejected promise gives the caller no partial array. A loop lets you save each successful page before asking for the next one.

Keep for await...of when you can process or save each page as it arrives, when you need to stop after the first match, or when the number of pages may exceed what you can keep in memory. Run the loop at the place that consumes the data so the export can make progress after the first page.