Async Iterators for Big Data Sets
An async iterator works like an ordinary iterator, except that its next() method returns a promise of { value, done } rather than the object itself. That lets each value arrive when it is ready, which suits data that comes from a server a page at a time. You consume an async iterator with for await...of, which waits for each promise before running the loop body.
This is useful when a data set is too large to request in one go. Instead of loading every record, you fetch one page, deal with it, and only then fetch the next, so memory use stays flat and you can stop as soon as you have what you need.
The async iteration protocol
Section titled “The async iteration protocol”An object is async iterable when it has a Symbol.asyncIterator method, which returns an object with an async next() method. This one produces three temperature readings, each after a short wait:
const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
const readings = { [Symbol.asyncIterator]() { let count = 0; return { async next() { await wait(100); count++; return count <= 3 ? { value: `reading ${count}: ${18 + count}°C`, done: false } : { value: undefined, done: true }; }, }; },};
for await (const reading of readings) { console.log(reading);}This prints:
reading 1: 19°Creading 2: 20°Creading 3: 21°CUse Symbol.asyncIterator for this, not Symbol.iterator. An object whose Symbol.iterator returns promises is a plain iterator of promises, so an ordinary for...of gets the promises themselves rather than their results.
for await...of can only be used where await is allowed, which means inside an async function or at the top level of an ES module. The examples on this page run as modules.
Paging through an API with an async generator
Section titled “Paging through an API with an async generator”An async generator, declared with async function*, writes the protocol for you. It can await inside, and each yield hands one value to the loop. This one asks the JSONPlaceholder test API for its to-do list fifty records at a time, and it stops when a page comes back empty:
async function* fetchTodos(pageSize) { let page = 1; while (true) { const url = `https://jsonplaceholder.typicode.com/todos?_page=${page}&_limit=${pageSize}`; const response = await fetch(url); if (!response.ok) { throw new Error(`Request failed: ${response.status}`); } const todos = await response.json(); if (todos.length === 0) return; yield todos; page++; }}
let pages = 0;let total = 0;for await (const batch of fetchTodos(50)) { pages++; total += batch.length;}console.log(`${total} to-dos in ${pages} pages`);This prints:
200 to-dos in 4 pagesThe generator does not request page two until the loop asks for the next value, so only one page is held in memory at a time. If a request fails, the error is thrown from the loop, where an ordinary try...catch can handle it.
Yielding one record at a time and stopping early
Section titled “Yielding one record at a time and stopping early”yield* hands out each item of an array in turn, so the loop sees single records instead of pages. Combined with break, this lets you stop as soon as you find what you want, and no further pages are requested:
async function* fetchTodos(pageSize) { let page = 1; while (true) { const url = `https://jsonplaceholder.typicode.com/todos?_page=${page}&_limit=${pageSize}`; const response = await fetch(url); if (!response.ok) { throw new Error(`Request failed: ${response.status}`); } const todos = await response.json(); if (todos.length === 0) return; console.log(`fetched page ${page}`); yield* todos; page++; }}
for await (const todo of fetchTodos(10)) { if (todo.completed) { console.log(`First completed to-do: #${todo.id} ${todo.title}`); break; }}This prints:
fetched page 1First completed to-do: #4 et porro temporaOnly the first page was fetched, because the loop stopped on the fourth record. The same pattern works for any source that delivers data in pieces, such as a database cursor or a file read in chunks. For Await Of Loop has more on the loop itself.
Steve Griffith covers this topic in his video Async Iterators for Big Data Sets.