Async Iteration in JavaScript: for await...of, Async Generators and Streams
Process data that arrives over time: the async iteration protocol and Symbol.asyncIterator, for await...of, async generators for paginated APIs and polling, Array.fromAsync, Node streams and events as async iterables, cleanup on break, error handling and the pitfalls.
kvi5hnuCode Sprout team member7 min readOn this page
A promise delivers one value later. Many sources deliver a sequence of values over time: pages of an API, lines of a large file, chunks of a network response, messages from a socket. Async iteration (ES2018) combines the iteration protocol from article 90 with promises, so you can loop over such sources with a plain-looking loop:
for await (const chunk of response.body) {
process(chunk);
}
The async iteration protocol
It mirrors the sync protocol from article 90, with promises added:
| Sync iteration | Async iteration | |
|---|---|---|
| method on the iterable | [Symbol.iterator]() | [Symbol.asyncIterator]() |
next() returns | { value, done } | a promise of { value, done } |
| loop | for...of | for await...of |
| generator | function* | async function* |

You can implement the protocol by hand, though you rarely need to:
const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
const countdown = {
from: 3,
[Symbol.asyncIterator]() {
let n = this.from;
return {
next: () => delay(5).then(() => (n > 0 ? { value: n--, done: false } : { value: undefined, done: true })),
};
},
};
async function main() {
for await (const n of countdown) console.log("t-minus", n);
console.log("liftoff");
}
main();
t-minus 3
t-minus 2
t-minus 1
liftoff
for await...of
for await...of may only appear where await is allowed: inside an async function, or at the top level of an ES module. Each round, it awaits the promise from next() and then runs the body. The next value isn't requested until the body finishes, so processing is strictly sequential, and a slow body naturally slows down the producer. This is called backpressure.
It also accepts sync iterables, awaiting each element. That works for an array of promises, but think twice before using it that way:
const delay = (ms, value) => new Promise((resolve) => setTimeout(resolve, ms, value));
async function main() {
const downloads = [delay(20, "a.zip"), "b.zip (cached)", delay(5, "c.zip")];
for await (const file of downloads) console.log(file);
}
main();
a.zip
b.zip (cached)
c.zip
The values come out in array order, but the promises were already running. If c.zip had rejected while the loop was still waiting for a.zip, nothing would be handling that rejection yet. For an array of promises, prefer Promise.all or allSettled (article 97).
Async generators
The easiest way to create an async iterable is an async generator: async function*. Inside it you can both await (wait for data) and yield (hand a value to the consumer).
const delay = (ms, value) => new Promise((resolve) => setTimeout(resolve, ms, value));
// fake API: three pages, each with a link to the next
const pagesOnServer = {
"/users?page=1": { items: ["ana", "ben"], next: "/users?page=2" },
"/users?page=2": { items: ["cy", "dee"], next: "/users?page=3" },
"/users?page=3": { items: ["eve"], next: null },
};
const fetchJson = (url) => delay(5, pagesOnServer[url]);
async function* allUsers(url) {
while (url) {
const page = await fetchJson(url);
console.log(` (fetched ${url})`);
yield* page.items; // hand out each item of this page
url = page.next;
}
}
async function main() {
for await (const user of allUsers("/users?page=1")) {
console.log(user);
if (user === "cy") break; // page 3 is never requested
}
}
main();
(fetched /users?page=1)
ana
ben
(fetched /users?page=2)
cy
This is the killer use case. The consumer doesn't know about pages or URLs; it just loops over users. The generator fetches lazily, one page at a time and only when needed, so breaking early saves requests. yield* delegates to another iterable (sync or async), just like in sync generators.
Cleanup, early exit and errors
As with sync generators (article 92), leaving the loop early with break, return or an exception calls the iterator's return() method, so finally blocks inside an async generator run. Use them to close connections or file handles:
async function* readRecords() {
console.log("open connection");
try {
yield "record 1";
yield "record 2";
yield "record 3";
} finally {
console.log("close connection");
}
}
async function main() {
for await (const record of readRecords()) {
console.log(record);
if (record === "record 2") break;
}
}
main();
open connection
record 1
record 2
close connection
Errors thrown inside the generator (or rejections it awaits) surface as exceptions in the loop, so a normal try...catch around for await handles them:
async function* flakyStream() {
yield "chunk 1";
throw new Error("connection lost");
}
async function main() {
try {
for await (const chunk of flakyStream()) console.log("got", chunk);
} catch (err) {
console.log("stream failed:", err.message);
}
}
main();
got chunk 1
stream failed: connection lost
Array.fromAsync
Array.fromAsync (supported in all major browsers since 2024 and in Node) collects an async iterable into an array, much as Array.from does for sync ones. It returns a promise:
const delay = (ms, value) => new Promise((resolve) => setTimeout(resolve, ms, value));
async function* squares(limit) {
for (let i = 1; i <= limit; i++) yield delay(2, i * i);
}
async function main() {
console.log(await Array.fromAsync(squares(4)));
console.log(await Array.fromAsync(squares(3), (n) => n + 0.5)); // optional mapping function
}
main();
[ 1, 4, 9, 16 ]
[ 1.5, 4.5, 9.5 ]
Only use it when the sequence is finite and fits in memory; the point of streaming is usually not to hold everything at once. If the source rejects, the promise from fromAsync rejects. (Yielding a promise inside an async generator yields its value, which is why squares produces numbers.)
Unlike sync iterators (article 93), async iterators don't yet have built-in map/filter/take helpers: async iterator helpers are still a TC39 proposal. Until then, write small async generators:
async function* map(source, fn) {
for await (const item of source) yield fn(item);
}
async function* take(source, count) {
if (count <= 0) return;
for await (const item of source) {
yield item;
if (--count <= 0) return;
}
}
async function* naturals() {
for (let n = 1; ; n++) yield n;
}
Array.fromAsync(take(map(naturals(), (n) => n * 10), 3)).then(console.log);
[ 10, 20, 30 ]
Writing an async iterator by hand
Async generators are convenient, but writing the iterator object directly gives you more control. Two situations where that matters:
Keeping a steady rhythm
A generator that does await sleep(interval) before each yield drifts: the wait only starts after the loop body has finished, so a slow body stretches every interval. An iterator whose next() aims for an absolute due time (start + n * interval) absorbs the time the body took:
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
async function* naiveTicks(intervalMs, count) {
for (let n = 1; n <= count; n++) {
await sleep(intervalMs); // waits a full interval after the body finished
yield n;
}
}
function scheduledTicks(intervalMs, count) {
const start = Date.now();
let n = 0;
return {
async next() {
if (n >= count) return { value: undefined, done: true };
n++;
await sleep(Math.max(0, start + n * intervalMs - Date.now())); // aim for an absolute time
return { value: n, done: false };
},
[Symbol.asyncIterator]() {
return this;
},
};
}
async function timeLoop(source) {
const start = Date.now();
for await (const tick of source) await sleep(15); // a slow loop body
return Date.now() - start;
}
async function main() {
const naive = await timeLoop(naiveTicks(20, 3));
const scheduled = await timeLoop(scheduledTicks(20, 3));
console.log("naive drifts (about 105 ms):", naive >= 100);
console.log("scheduled stays on time (about 75 ms):", scheduled < naive);
}
main();
naive drifts (about 105 ms): true
scheduled stays on time (about 75 ms): true
Declaring next as async makes it return a promise automatically. Because the iterator returns itself from [Symbol.asyncIterator](), it works directly with for await.
Turning events into an async iterable
Events are pushed at you by a callback, but for await pulls values with next(). To connect the two you need a queue that handles both orders:
- an event arrives before anyone asked for it: buffer the value;
next()is called before any event arrived: hand out a pending promise and resolve it when the event comes.
class EventQueue {
#buffer = [];
#waiting = [];
#closed = false;
push(value) {
if (this.#closed) throw new Error("queue is closed");
const waiter = this.#waiting.shift();
if (waiter) waiter.resolve({ value, done: false });
else this.#buffer.push(value);
}
close() {
this.#closed = true;
for (const waiter of this.#waiting.splice(0)) waiter.resolve({ value: undefined, done: true });
}
next() {
if (this.#buffer.length > 0) return Promise.resolve({ value: this.#buffer.shift(), done: false });
if (this.#closed) return Promise.resolve({ value: undefined, done: true });
const waiter = Promise.withResolvers();
this.#waiting.push(waiter);
return waiter.promise;
}
[Symbol.asyncIterator]() {
return this;
}
}
const orders = new EventQueue();
orders.push("order #1"); // arrives before anyone is listening
setTimeout(() => orders.push("order #2"), 10);
setTimeout(() => orders.push("order #3"), 20);
setTimeout(() => orders.close(), 30);
async function main() {
for await (const order of orders) console.log("processing", order);
console.log("queue closed");
}
main();
processing order #1
processing order #2
processing order #3
queue closed
Promise.withResolvers() (article 95) keeps each waiting caller's resolve function until a value turns up. In a browser, the same queue can feed clicks into a loop:
const clicks = new EventQueue();
button.addEventListener("click", (event) => clicks.push(event));
for await (const click of clicks) {
await saveDraft(); // clicks that arrive meanwhile wait their turn in the queue
}
This is roughly what Node's events.on() does internally (shown below), and libraries offer polished versions with error handling and buffer limits.
Real-world async iterables
Many platform APIs are async iterable, so for await is how you consume them:
Node.js readable streams (files, HTTP request bodies, process.stdin):
const { Readable } = require("node:stream");
async function main() {
const stream = Readable.from(["The quick ", "brown fox ", "jumps"]);
let text = "";
for await (const chunk of stream) text += chunk;
console.log(text);
}
main();
The quick brown fox jumps
Reading a large file line by line, without loading it all into memory:
import { createReadStream } from "node:fs";
import { createInterface } from "node:readline";
const lines = createInterface({ input: createReadStream("server.log"), crlfDelay: Infinity });
let errors = 0;
for await (const line of lines) {
if (line.includes("ERROR")) errors++;
}
console.log(`${errors} error lines`);
Node events: events.on(emitter, name) turns repeated events into an async iterable (break to stop listening):
const { EventEmitter, on } = require("node:events");
async function main() {
const sensor = new EventEmitter();
setTimeout(() => {
sensor.emit("reading", 21.5);
sensor.emit("reading", 22.1);
sensor.emit("reading", 22.8);
}, 5);
let count = 0;
for await (const [celsius] of on(sensor, "reading")) {
console.log("temperature", celsius);
if (++count === 3) break;
}
}
main();
temperature 21.5
temperature 22.1
temperature 22.8
Web streams: a fetch response body is a ReadableStream, and readable streams are async iterable in Node, Deno and modern browsers. Paired with TextDecoderStream, that lets you process a large or streamed response (such as server-sent AI output) as it arrives:
const response = await fetch("/api/stream");
const textStream = response.body.pipeThrough(new TextDecoderStream());
for await (const text of textStream) {
appendToPage(text);
}
When to use what
- One future value: a promise,
await. - A fixed set of values you want concurrently:
Promise.all/allSettled. - A sequence that arrives over time, processed in order: an async iterable with
for await. - Events that keep firing and that you may never stop listening to (clicks, for example): plain event listeners are usually simpler.
Common questions
Can I use for await...of with a regular array?
Yes. It awaits each element, so it works with an array of promises, but the promises are already running, and a rejection that happens before the loop reaches it can go unhandled. Use Promise.all for arrays of promises.
Does for await process items in parallel?
No. It requests the next item only after the body finishes with the current one. For parallelism, collect the work and use Promise.all, or use a concurrency-limited helper.
What's the difference between an async generator and a generator that yields promises?
A sync generator that yields promises gives you { value: promise, done } immediately and can't wait internally. An async generator can await between yields, and its next() itself returns a promise, so for await works naturally and early exit runs finally correctly.
How do I stop an async iteration from outside?
Break out of the loop, or call iterator.return(). Many platform APIs (events.on, fetch) also accept an AbortSignal so the source itself can be cancelled.
Summary
- Async iterables implement
[Symbol.asyncIterator](), whosenext()returns a promise of{ value, done }. for await...ofconsumes them sequentially, one item at a time, inside async functions or modules.async function*combinesawaitandyield: ideal for pagination, polling and lazy streaming.breakor an error callsreturn(), sofinallyblocks run; errors from the source become exceptions in the loop.Array.fromAsynccollects finite async iterables; async iterator helpers are still a proposal.- Node streams, readline,
events.onand webReadableStreams are all async iterable.
Practice Questions
What does this print?
async function* gen() {
yield 1;
yield 2;
}
const it = gen();
console.log(it.next() instanceof Promise);
Answer
true. An async generator's next() returns a promise for the { value, done } result.
Write an async generator poll(fn, ms) that calls the async function fn every ms milliseconds and yields each result forever. How does the consumer stop it?
Answer
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
async function* poll(fn, ms) {
while (true) {
yield await fn();
await sleep(ms);
}
}
for await (const status of poll(getStatus, 1000)) {
if (status === "done") break; // break calls return() and stops polling
}
When the consumer breaks out of this loop after the first line, what is logged, and does the file stay open?
async function* lines(file) {
const handle = await open(file);
try {
for await (const line of handle.readLines()) yield line;
} finally {
await handle.close();
console.log("closed");
}
}
Answer
closed is logged and the file doesn't stay open. break calls the generator's return(), which runs the finally block and closes the handle.
Why might this program crash with an unhandled rejection even though it has a try/catch?
const ps = [slowOk(), fastFail()];
try {
for await (const v of ps) console.log(v);
} catch (e) {
console.log("handled");
}
Answer
Both promises start immediately. fastFail() rejects while the loop is still awaiting slowOk(), and at that moment no handler is attached to it, so the runtime reports an unhandled rejection (which crashes Node). Use await Promise.all(ps) or allSettled instead.
Previous: JavaScript async and await: Writing Asynchronous Code That Reads Like Synchronous Code
Next: Explicit Resource Management in JavaScript: using, await using and DisposableStack

More in JavaScript Course
Quiz: Modern JavaScript, ES2022 to ES2027 Features
Twenty-four questions on what's new in JavaScript: change-array-by-copy methods, groupBy, Set methods, iterator helpers, Promise.withResolvers and Promise.try, RegExp.escape and the v flag, using declarations, Error.isError, Base64 typed arrays, Temporal, getOrInsert and Iterator.zip.
Quiz: JavaScript's Delicate Details (Spec-Level Edge Cases)
Twenty-eight questions on the fine print of JavaScript, drawn from the ECMAScript specification and MDN: sparse arrays, -0, number limits, JSON edge cases, Date overflow, UTF-16, property attributes, inherited accessors, comparison quirks, labels, regex state and Symbol.toPrimitive.
Quiz: JavaScript Interview Questions (Output Prediction and Core Concepts)
Thirty classic JavaScript interview questions: closures in loops, hoisting and the TDZ, this, the event loop and microtasks, async/await, coercion, sorting and parseInt traps, prototypes, copying, finally, generators and bind. Every answer was verified by running it.
Quiz: JavaScript Course Final Exam (All 17 Parts)
The final exam for the JavaScript course: thirty questions spanning all seventeen parts, from syntax, types and operators through objects, arrays, functions, classes, modules, the standard library, iterators, async code, metaprogramming, browsers, Node.js and tooling.
Discussion
Sign in to ask a question or share what you learned.