liveBook · Manning

For await loop

As explained in JavaScript in Depth

A JavaScript loop construct that asynchronously obtains successive values from an async iterable and propagates iteration failures as thrown exceptions.

A for await loop consumes an async iterable one value at a time. Each iteration calls next(), awaits its promise, checks done, and runs the body before requesting another value. That sequencing creates a strict pull model: the consumer controls when production continues. section 10.5

The loop’s behavior follows a small protocol:

  • Require an object whose Symbol.asyncIterator method returns an iterator. section 10.5
  • Call next() and await the promise resolving to { value, done }. section 10.5
  • Delay the next call until the current promise resolves and the loop body finishes. section 10.5
  • Catch a rejected next() promise with try/catch surrounding the loop. section 10.6.1

Consuming an async generator

An async generator can fetch and yield pages incrementally. The consumer’s await processPage(page) keeps the generator suspended, so data does not accumulate while processing is slower than fetching. section 10.5.1

const readable = fs.createReadStream('large-file.txt');
for await (const chunk of readable) {
  await processChunk(chunk);
}

Use the loop to consume a Node.js Readable chunk by chunk, while remembering that the stream still buffers data through its push-based internals. section 10.5.3

How JavaScript in Depth covers it

How deep it goes
Explains protocol calls, awaiting, sequencing, backpressure, and error propagation, but not compiler implementation internals.
Examples
Uses hand-written async iterables, Node.js Readables, async generators fetching pages, and try/catch around iteration.
What it assumes
Assumes promises and iteration basics while defining the async iteration protocol from its required methods.
What you can do after
Apply it to consume async iterables and handle iteration failures with ordinary try/catch.
How it connects
Connects async iterables, async generators, backpressure, Node.js streams, Web Streams, and promise rejection.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of JavaScript in Depth. The section links point to the parts of the book it draws on.