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
