Async Iteration and for await
When each value arrives separately over time, an async iterator lets you loop over them as they come.
Symbol.asyncIterator returns an iterator whose next returns a promise. for await consumes it, pausing on each value. An async generator writes one in a few lines, and paginated APIs and streams are the natural fit.
EXERCISE
1Looping Over Values That Arrive Later
A normal iterator produces values immediately. An async one produces promises, and a different loop unwraps them.
Everything so far assumed the next value is available now. Often it is not: pages of an , lines of a file, messages on a socket.
The async protocol, which mirrors the sync one:
// Symbol.iterator -> next() returns { value, done }
// Symbol.asyncIterator -> next() returns a Promise of { value, done }
for await consumes it:
async function* ticker() {
for (let i = 1; i <= 3; i++) {
await delay(1000);
yield i;
}
}
for await (const tick of ticker()) {
console.log(tick);
}
// 1 (after 1s)
// 2 (after 2s)
// 3 (after 3s)
async function* is an async generator: it may await inside and it yields values that arrive over time. The loop waits for each one.
for await also works on an array of promises, which is a useful shortcut:
const promises = [fetch("/a"), fetch("/b"), fetch("/c")];
for await (const response of promises) {
console.log(response.status);
}
All three requests started when the array was built, so they run concurrently. The loop unwraps them in order. That is different from a normal for...of, which would hand you the promise objects themselves.
The natural fit is pagination:
async function* allUsers() {
let page = 1;
while (true) {
const response = await fetch(`/api/users?page=${page}`);
const { users, hasMore } = await response.json();
yield* users;
if (!hasMore) return;
page += 1;
}
}
for await (const user of allUsers()) {
console.log(user.name);
if (user.name === "Ada") break;
}
The consumer writes an ordinary loop and never mentions pages. It fetches one page, yields each user from it, and only requests the next page when the loop asks for more. If the caller breaks early, no further requests are made at all.
That laziness is the whole point. The alternative, fetching every page into an array first, does work the consumer may not need and holds it all in memory.
Reach for an async generator when values arrive over time and the consumer might not want all of them. Pagination, log tailing and event streams all fit. If you genuinely need every value before you can start, Promise.all is simpler and runs concurrently rather than in sequence.
EXERCISE
2Ordering, Errors and Cleanup
for await is sequential by nature, which is right for a stream and wrong for a list of independent work.
for await waits for each value before requesting the next:
async function* slowly() {
yield await slow(300);
yield await slow(300);
yield await slow(300);
}
for await (const v of slowly()) {
console.log(v);
}
// about 900ms total
This is Unit 6's sequencing point in a new place. The generator cannot produce the second value until the first has been consumed, so the work is serial by construction.
When the items are independent, that is the wrong tool:
// Sequential: 900ms
for await (const r of [slow(300), slow(300), slow(300)]) { /* ... */ }
// Wait: these all started already, so this one is 300ms.
// Truly sequential, and usually accidental:
for (const url of urls) {
const r = await fetch(url); // one at a time
}
// Concurrent:
const all = await Promise.all(urls.map((u) => fetch(u)));
The distinction that matters: for await over an array of already-created promises is concurrent, because creating them started the work. for await over an async generator is sequential, because the generator does not start the next item until asked.
Errors propagate to the loop and can be caught normally:
async function* risky() {
yield 1;
throw new Error("stream failed");
}
try {
for await (const v of risky()) {
console.log(v); // 1
}
} catch (err) {
console.log("caught:", err.message); // caught: stream failed
}
A try around the loop covers both the generator's failures and the loop body's, which is the same unification async/await gave you in Unit 6.
Cleanup runs when the consumer leaves early:
async function* readLines(file) {
const handle = await open(file);
try {
let line;
while ((line = await handle.readLine()) !== null) {
yield line;
}
} finally {
await handle.close(); // runs on break, on throw, and on completion
}
}
for await (const line of readLines("big.log")) {
if (line.includes("ERROR")) break;
}
// the file handle is closed
Breaking out of a for await calls the generator's return, which runs the finally. That is why a try/finally around a resource inside an async generator is a genuinely reliable pattern, and it is the main reason to prefer one over a manual loop for anything holding a handle, a connection or a subscription.
And the sync and async protocols do not mix:
const gen = asyncGen();
// for (const v of gen) { }
// TypeError: gen is not iterable
for await (const v of gen) { /* ... */ } // correct
An object can implement both if it makes sense, but one does not substitute for the other.
Pro Tip: Put any resource an async generator opens inside a
try/finally. Consumers break out of loops all the time, often in code you will never see, and thefinallyis what guarantees the handle closes anyway. Without it, an earlybreakleaks the resource silently.
EXERCISE
3Streams, Events and Backpressure
Async iteration is how modern JavaScript consumes anything that produces values over time.
The protocol is not only for code you write. Several platform APIs already implement it.
Node streams are async iterable:
import { createReadStream } from "node:fs";
import { createInterface } from "node:readline";
const lines = createInterface({
input: createReadStream("big.log"),
});
for await (const line of lines) {
if (line.includes("ERROR")) {
console.log(line);
}
}
A file of any size, read line by line, with constant memory. The alternative, readFileSync and split("\\n"), holds the entire file and every line in memory at once.
Web streams work the same way:
const response = await fetch("/api/large-export");
for await (const chunk of response.body) {
process(chunk); // a Uint8Array per chunk
}
You can start handling the beginning of a response before the end has arrived, which matters for a large download or a server-sent stream.
Turning an event source into an async iterable:
async function* events(target, name) {
const queue = [];
let resolveNext = null;
target.addEventListener(name, (event) => {
if (resolveNext) {
resolveNext(event);
resolveNext = null;
} else {
queue.push(event);
}
});
while (true) {
if (queue.length > 0) {
yield queue.shift();
} else {
yield await new Promise((resolve) => {
resolveNext = resolve;
});
}
}
}
for await (const click of events(button, "click")) {
console.log("clicked at", click.clientX);
}
Worth reading slowly. When a consumer is waiting, the event goes straight to it. When nobody is waiting, it is queued. That queue is the whole reason this is not trivial, and it is where the term backpressure comes from: the producer is faster than the consumer, so something has to hold the excess.
This version's queue grows without limit, which is fine for clicks and wrong for a high-rate source. A real implementation caps it and drops or blocks when full.
Why this matters as a shape:
// Pull-based: the consumer asks, so it sets the pace.
for await (const item of source) { /* ... */ }
// Push-based: the producer calls you, at whatever rate it likes.
source.addEventListener("data", handler);
An event listener cannot say "not yet". An async iterator can simply not call next, and the producer has to wait. That is the practical difference, and it is why streaming APIs moved towards this protocol.
Pro Tip: When you find yourself buffering everything an event source emits so you can process it later, that is the signal to reach for an async iterator instead. Pull-based consumption lets you go at your own speed, and
for awaitwith atry/finallygives you cleanup on early exit for free.
