Async iteration: for await...of and generators (ES2018)
What you’ll learn
Section titled “What you’ll learn”- The async iteration protocol:
Symbol.asyncIteratorand anext()that returns a promise. - How
for await...ofconsumes async and sync iterables, and where you are allowed to write it. - How to write async generators that page through an API or read a stream, and clean up in
finally. - Why
for awaitover an array of running promises can crash a Node.js process, and what to do instead. - Where
Array.fromAsync()(ES2026) and still-proposed async iterator helpers fit in.
Summary
Section titled “Summary”TL;DR: an async iterable is an object with a [Symbol.asyncIterator]() method whose iterator’s next() returns a promise of { value, done }. for await (const x of source) awaits each step, so you can loop over data that arrives over time: pages from an API, lines from a file, messages from a socket. An async function* is the easy way to produce one: it can both await and yield.
Async iteration was added in ECMAScript 2018 and works in all current browsers and server runtimes (see Compatibility).
The problem it solves
Section titled “The problem it solves”for...of needs every value to be ready when next() is called. Before ES2018, data that arrived over time meant callbacks, event emitters, or a hand-written while loop over promises that mixed “fetch the next page” logic with “process each item” logic. Async iteration separates the two: the producer decides when and how to fetch, the consumer writes an ordinary loop.
Running the samples: save each complete sample as a .mjs file and run it with Node.js 22 (node sample.mjs). The samples use top-level await and for await, which ES modules allow at the top level. The outputs shown were produced with Node.js 22.23.
// OrdersPortal: a fake paged API. Each call resolves after a short delay.const PAGES = [['o-1', 'o-2'], ['o-3', 'o-4'], ['o-5']];async function fetchPage(cursor) { await new Promise((r) => setTimeout(r, 10)); const index = cursor ?? 0; const next = index + 1 < PAGES.length ? index + 1 : null; console.log(` fetched page ${index}`); return { items: PAGES[index], next };}
// An async generator: pull one page at a time, yield one order at a time.async function* allOrders() { let cursor = null; do { const page = await fetchPage(cursor); yield* page.items; cursor = page.next; } while (cursor !== null);}
for await (const id of allOrders()) { console.log('order', id); if (id === 'o-3') break; // page 2 is never requested}Output:
fetched page 0order o-1order o-2 fetched page 1order o-3Iteration is pull-based: the generator fetches the next page only when the loop asks for more, and stops completely after break.
How it works
Section titled “How it works”The protocol
Section titled “The protocol”// Fragment: shapesasyncIterable[Symbol.asyncIterator]() // -> asyncIteratorasyncIterator.next() // -> Promise<{ value, done }>asyncIterator.return?.() // -> Promise<{ value, done }>, called on early exitWriting the protocol by hand shows each part:
const countdown = { [Symbol.asyncIterator]() { let n = 3; return { next: () => new Promise((resolve) => setTimeout(() => resolve(n > 0 ? { value: n--, done: false } : { value: undefined, done: true }), 5)), return: () => { console.log('return() called'); return Promise.resolve({ done: true }); }, }; },};for await (const n of countdown) console.log(n);for await (const n of countdown) { console.log('early', n); break; }
// for await also accepts sync iterables; each value is awaited.for await (const v of [Promise.resolve('a'), 'b']) console.log('sync source:', v);
const gen = (async function* () { yield 1; })();console.log(typeof gen[Symbol.asyncIterator], typeof gen.next().then);Output:
321early 3return() calledsync source: async source: bfunction functionfor await...of rules
Section titled “for await...of rules”- It is allowed inside
asyncfunctions, async generators and at the top level of ES modules. Anywhere else it is aSyntaxError. - It first looks for
Symbol.asyncIterator. If there is none, it falls back toSymbol.iteratorand awaits each value, which is why arrays of promises “work” (with a trap, below). - On
break,return,throwor an outercontinue, it calls and awaits the iterator’sreturn(), the same closing rule asfor...of. - If
next()rejects, the loop throws that error at the loop statement; wrap it intry...catch. - There is no
for await...in.
Async generators
Section titled “Async generators”An async function* returns an object that is both the async iterator and its own async iterable.
yield valueawaitsvaluefirst, so yielding a promise delivers its result.yield* sourcedelegates to another async iterable (or a sync one).return()from the consumer runs pendingfinallyblocks, which is where you close files, sockets and cursors.- Calls to
next()are queued: the generator handles one request at a time, in order. Callingnext()three times without waiting does not run anything in parallel.
const delay = (ms, v) => new Promise((r) => setTimeout(() => r(v), ms));async function* numbers() { console.log('start'); yield delay(20, 'awaited value'); // yield awaits its operand yield 'second';}const it = numbers();// Calls made without waiting are queued, not run in parallel.const results = await Promise.all([it.next(), it.next(), it.next()]);console.log(results);Output:
start[ { value: 'awaited value', done: false }, { value: 'second', done: false }, { value: undefined, done: true }]Realistic example
Section titled “Realistic example”OrdersPortal exports orders as NDJSON (one JSON object per line). Node.js readline interfaces and readable streams are async iterables, so the import is a pipeline of small async generators: parse lines, then filter. Nothing is buffered beyond the current chunk, so the same code handles a 10-line file and a 10 GB one.
import { writeFile, rm } from 'node:fs/promises';import { createReadStream } from 'node:fs';import { createInterface } from 'node:readline';
// OrdersPortal export: one JSON order per line (NDJSON).const file = new URL('./orders.ndjson', import.meta.url);await writeFile(file, [ '{"id":"o-1","total":40}', '{"id":"o-2","total":15.5}', '', '{"id":"o-3","total":120}',].join('\n'));
async function* parseOrders(path) { const lines = createInterface({ input: createReadStream(path), crlfDelay: Infinity }); let lineNo = 0; for await (const line of lines) { lineNo++; if (line.trim() === '') continue; try { yield JSON.parse(line); } catch (cause) { throw new Error(`bad JSON on line ${lineNo}`, { cause }); } }}
async function* largeOrders(orders, min) { for await (const order of orders) if (order.total >= min) yield order;}
let count = 0;for await (const order of largeOrders(parseOrders(file), 20)) { count++; console.log('large order', order.id, order.total);}console.log('large orders:', count);
console.log(await Array.fromAsync(parseOrders(file), (o) => o.id));await rm(file);Output:
large order o-1 40large order o-3 120large orders: 2[ 'o-1', 'o-2', 'o-3' ]If the consumer breaks out early, return() travels down the chain: largeOrders closes parseOrders, which closes the readline interface and the file stream. Array.fromAsync() collects an async iterable into an array; use it only when the result fits in memory.
Production patterns
Section titled “Production patterns”Bounded concurrency without losing order
Section titled “Bounded concurrency without losing order”A plain for await loop processes one item at a time. To keep a few requests in flight and still yield results in order, start promises ahead of the consumer and attach a no-op catch so an early failure is not reported as unhandled before you reach it:
const delay = (ms, v) => new Promise((r) => setTimeout(() => r(v), ms));async function* mapConcurrent(source, limit, fn) { const window = []; for (const item of source) { const p = fn(item); p.catch(() => {}); // mark handled; the error is rethrown when awaited below window.push(p); if (window.length >= limit) yield await window.shift(); } while (window.length) yield await window.shift();}
const started = Date.now();const ids = ['o-1', 'o-2', 'o-3', 'o-4'];for await (const r of mapConcurrent(ids, 2, (id) => delay(50, `${id} loaded`))) { console.log(r);}console.log('elapsed ~', Math.round((Date.now() - started) / 50) * 50, 'ms (sequential would be ~200)');Output (timing varies slightly):
o-1 loadedo-2 loadedo-3 loadedo-4 loadedelapsed ~ 100 ms (sequential would be ~200)For cancellation, pass an AbortSignal into fn and abort it in the generator’s finally, so a break in the consumer also stops in-flight requests.
Common mistakes
Section titled “Common mistakes”-
for awaitover an array of already-running promises. The loop handles them one at a time. If a later promise rejects while the loop is still awaiting an earlier one, that rejection has no handler yet: Node.js treats it as unhandled and exits with code 1 before thecatchruns.const delay = (ms, value, fail = false) =>new Promise((resolve, reject) => setTimeout(() => (fail ? reject(new Error(value)) : resolve(value)), ms));process.on('exit', (code) => console.log('exit code', code));const requests = [delay(50, 'slow ok'), delay(10, 'fast failure', true)];try {for await (const result of requests) console.log(result);} catch (error) {console.log('caught:', error.message); // never reached}Output (stdout and stderr combined, stack trace shortened;
slow okandcaught:never print):exit code 1file:///.../sample.mjs:2...Error: fast failureat Timeout._onTimeout (file:///.../sample.mjs:2:68)Use
Promise.allorPromise.allSettledfor a fixed set of promises, or the bounded pattern above. -
Expecting parallelism from an async generator. Its
next()calls are queued and run one at a time. -
Clean-up outside
finally. Code after the loop in a generator never runs when the consumer breaks; onlyfinallydoes. -
Forgetting that
for awaitis sequential. Ten slow requests in a loop body take ten times as long: right for ordered or rate-limited work, wrong otherwise. -
Writing
for awaitin a non-async function or classic script. It is aSyntaxErroroutside async functions and module top level.
When to use it and when not to
Section titled “When to use it and when not to”| Situation | Use |
|---|---|
| Data arrives in pieces over time (pages, lines, messages) | for await...of with an async generator |
Node.js readable streams, readline, events.on() |
for await...of directly |
| A fixed list of promises you already started | Promise.all / Promise.allSettled |
| Push-based events with many listeners or back-pressure operators | Event emitters, EventTarget or a streams library |
| You need the whole result as an array | Array.fromAsync() (ES2026) or collect in the loop |
| All values are available synchronously | for...of |
Async iterator helpers (map, filter, take on async iterators) are a Stage 2 TC39 proposal as of November 2026, not part of the language. Write small async generators like largeOrders instead.
Compatibility
Section titled “Compatibility”According to MDN’s compatibility data, for await...of and async generator functions are supported in Chrome 63, Edge 79, Firefox 57, Safari 12, Node.js 10.0.0, Deno 1.0 and Bun 1.0. Internet Explorer never supported them. Array.fromAsync() is part of ECMAScript 2026 and is supported in Chrome 121, Edge 121, Firefox 115, Safari 16.4, Node.js 22.0.0, Deno 1.38 and Bun 1.0. In TypeScript, the types live in the es2018.asynciterable and es2018.asyncgenerator libs.
Interview questions
Section titled “Interview questions”1. What is the difference between Symbol.iterator and Symbol.asyncIterator?
Both return an iterator, but a sync iterator’s next() returns { value, done } directly, while an async iterator’s next() returns a promise for it. for...of uses only Symbol.iterator; for await...of prefers Symbol.asyncIterator and falls back to Symbol.iterator, awaiting each value.
2. What happens when you break out of a for await loop over an async generator?
The loop calls the generator’s return() and awaits it. The generator resumes as if return ran at the paused yield, its finally blocks run (and may await clean-up), and the generator is finished.
3. Why is for await (const r of arrayOfPromises) risky?
The promises are already running, but the loop only attaches a handler to one at a time. A rejection in a promise the loop has not reached yet is unhandled at that moment, which crashes Node.js by default and fires unhandledrejection in browsers. Use Promise.all or allSettled, or attach handlers up front.
4. Do async generators run their work in parallel if you call next() several times?
No. Requests are queued and served one by one in order. To overlap I/O, start several promises yourself inside the generator, as in a bounded-concurrency window.
5. Senior scenario: you must sync every order from a paged partner API into your database, the API allows five concurrent requests, and the job must stop cleanly on shutdown. How do you design it?
Model the source as an async generator that follows the cursor and yields pages, so paging logic lives in one place. Process items through a bounded window of five in-flight requests. Pass an AbortSignal from the shutdown handler into every request and break out of the loop on abort, so return() runs each generator’s finally and releases connections. Persist the last committed cursor after each page so a restart resumes, and retry transient failures with backoff inside the producer.
Key takeaways
Section titled “Key takeaways”- Async iteration (ES2018) is the iterator protocol with promises:
Symbol.asyncIterator,next()returning a promise, andfor await...of. - Async generators combine
awaitandyieldand are the simplest way to build streaming pipelines. - Iteration is pull-based and sequential; early exit calls
return(), so put clean-up infinally. - Do not use
for awaitover arrays of running promises; use promise combinators or a bounded window. Array.fromAsync()is ES2026; async iterator helpers are still a proposal.
Related pages
Section titled “Related pages”- for…of: the synchronous loop and its closing rules.
- Iterators and iterables and Generators: the sync protocol this builds on.
- Async/Await: the
awaitused throughout. - Top-level await: why the samples can use
for awaitat module top level. - Promise.allSettled: for a fixed set of independent promises.
- Node.js streams: readable streams are async iterables.
- Asynchronous programming basics
Official references
Section titled “Official references”- ECMAScript Language Specification: The
for-in,for-of, andfor-await-ofStatements (current draft) - ECMAScript specification: AsyncGenerator objects
- ECMAScript 2018 Language Specification (ECMA-262, 9th edition)
- TC39 proposal: Asynchronous iteration
- TC39 proposal: Array.fromAsync and Async iterator helpers (Stage 2)
- MDN: for await…of
- MDN: async function*
- MDN: Array.fromAsync()
- Node.js 22: readline
rl[Symbol.asyncIterator]()