Hello! Welcome to the third lesson in our module on Advanced Asynchronous Patterns.
In our last two lessons, we explored the async iterator protocol, first by implementing it manually and then by using the much cleaner async function* syntax to create async generators. We've consistently used the for await...of loop to consume the data from these asynchronous sources, but we've treated it as a piece of "magic" that just works.
Today, we're going to demystify that magic. Our goal is to use for-await-of loops to iterate over async iterables and async generators, but with a deep understanding of how and why they work. We'll dissect the loop's mechanics, explore its precise behavior, and clarify what makes it different from a standard for...of loop.
1. The Need for a New Kind of Loop
You might wonder why a special loop is necessary at all. Why can't a regular for...of loop handle an async generator? It's a great question, and the answer gets to the heart of the JavaScript iteration protocols.
A for...of loop is designed for synchronous iteration. It expects the object it's iterating over to have a [Symbol.iterator] method. This method returns an iterator whose next() method returns a plain object like { value: ..., done: false } synchronously.
Async generators and other async iterables, however, operate on a different protocol: asynchronous iteration. Their next() method returns a Promise that resolves to { value: ..., done: false }. The for...of loop doesn't know how to await these promises.
Welcome to Async Generators in JavaScript
To see this in action, let's watch a short segment from the video 'Welcome to Async Generators in JavaScript' by Andrew Burgess. It clearly demonstrates the error you get when using the wrong loop and introduces for await...of as the solution.
Watch from 01:42 to 03:00. Pay close attention to the error message when await is removed from the for await...of loop. The key insight is that an async generator does not have a [Symbol.iterator] method; it has a [Symbol.asyncIterator] method.
This establishes the core rule:
for...ofis for synchronous iterables ([Symbol.iterator]).for await...ofis for asynchronous iterables ([Symbol.asyncIterator]).
2. The Asynchronous Iteration Protocol
Let's formalize what it means for an object to be an async iterable, which is the requirement for for await...of to work.
Async iteration and generators
The article 'Async iteration and generators' from javascript.info provides a very clear definition of the protocol.
Read the section 'Async iterables'. Focus on the three rules for making an object asynchronously iterable and study the range example. The small table comparing synchronous and asynchronous iterators is an excellent summary.
To summarize the key points from the article:
- The object must have a method at
[Symbol.asyncIterator]. - This method must return an iterator object.
- The iterator's
next()method must return aPromisewhich resolves to an object like{ value: 'some-value', done: false }.
This is the "contract" that for await...of expects. Both async generators and the manual async iterators you built earlier fulfill this contract.
3. Under the Hood: Deconstructing the Loop
The for await...of syntax is essentially syntactic sugar over a while loop that manually calls iterator.next() and awaits the result. Understanding this "desugared" version is crucial for a deep comprehension of its behavior.
Given your CS background, you can think of this as how a higher-level language feature is compiled down to more fundamental operations.
Conceptually, a loop like this:
for await (const value of asyncIterable) {
// ... do something with value
}
Is executed by the JavaScript engine in a way similar to this:
// 1. Get the async iterator from the iterable
const asyncIterator = asyncIterable[Symbol.asyncIterator]();
// 2. Loop until the iterator is done
while (true) {
// 3. Get the next result, which is a promise
const resultPromise = asyncIterator.next();
// 4. Wait for the promise to resolve
const result = await resultPromise;
// 5. If it's done, exit the loop
if (result.done) {
break;
}
// 6. Otherwise, use the value
const value = result.value;
// ... do something with value
}
This manual breakdown makes the process transparent. There's no magic—just a well-defined sequence of getting an iterator, calling next(), awaiting the promise, and checking the done flag.
Async iterators (for await ... of) in JavaScript
The video 'Async iterators (for await ... of) in JavaScript' by Fun Fun Function provides a fantastic demonstration of this manual unwrapping.
Watch from 11:11 to 13:02. The presenter manually gets the iterator and calls await iterator.next() multiple times, logging the result. This shows you exactly what the for await...of loop is abstracting away.
4. Practical Consumption
With a solid grasp of the mechanics, let's look at for await...of consuming both of the async iterable types we've discussed.
Consuming an Async Generator
This is the use case you saw in the last lesson. It's clean and concise because the generator function implicitly creates the async iterable object for you.
// An async generator that yields numbers with a delay
async function* countWithDelay(limit) {
for (let i = 1; i <= limit; i++) {
await new Promise(resolve => setTimeout(resolve, 500));
yield i;
}
}
// Consuming it with for await...of
(async () => {
console.log("Starting countdown...");
for await (const number of countWithDelay(3)) {
console.log(number);
}
console.log("Countdown finished!");
})();
// Output:
// Starting countdown...
// (waits 0.5s)
// 1
// (waits 0.5s)
// 2
// (waits 0.5s)
// 3
// Countdown finished!
Consuming a Manual Async Iterable
The loop works identically for a manually created async iterable, proving that it only cares about the protocol, not the implementation. We can use the async range object from the javascript.info article as a perfect example.
Async iteration and generators
Let's revisit the javascript.info article to see the for await...of loop used on a non-generator object that correctly implements the async iterable protocol.
Review the section titled 'Async iterable range'. Notice how the same for await (let value of range) syntax works perfectly, even though the range object uses an async generator as its [Symbol.asyncIterator] implementation rather than being a generator itself.
5. Advanced Behavior and Common Gotchas
Understanding the basic mechanics is one thing; mastering the nuances is what makes you an advanced developer.
Sequential, Not Parallel
A very common misconception is that for await...of might fetch values concurrently. It does not. It is strictly sequential. The loop will await the promise from one next() call to be fully resolved before it ever calls next() again.
Consider this example:
async function* slowValues() {
console.log('Fetching first value...');
await new Promise(resolve => setTimeout(resolve, 1000));
yield 1;
console.log('Fetching second value...');
await new Promise(resolve => setTimeout(resolve, 1000));
yield 2;
console.log('Fetching third value...');
await new Promise(resolve => setTimeout(resolve, 1000));
yield 3;
}
(async () => {
const start = Date.now();
console.log('Loop started.');
for await (const num of slowValues()) {
console.log(`Received: ${num}`);
}
const end = Date.now();
console.log(`Loop finished in ${end - start}ms.`);
})();
The output will show that the total time is approximately 3000ms. The loop waits for each 1000ms delay to finish before even starting the next one. This is by design, ensuring ordered processing for data streams where each value might depend on the last. If you need concurrency, patterns like Promise.all() are more appropriate.
Error Handling
If the promise returned by iterator.next() rejects, the for await...of loop will throw an error. This means you can—and should—wrap the loop in a standard try...catch block to handle potential failures during iteration.
async function* faultyGenerator() {
yield 'First value';
await new Promise(resolve => setTimeout(resolve, 500));
throw new Error('Something went wrong!');
// This value will never be yielded
yield 'Second value';
}
(async () => {
try {
for await (const value of faultyGenerator()) {
console.log(value);
}
} catch (err) {
console.error(`Caught an error: ${err.message}`);
}
})();
// Output:
// First value
// (waits 0.5s)
// Caught an error: Something went wrong!
Loop Termination and Cleanup
You can use break and continue inside a for await...of loop just like in a regular loop. When a loop is terminated early with break, return, or by throwing an error, the JavaScript engine checks if the iterator has a .return() method. If it does, it calls it. This allows the iterator to perform cleanup, like closing a file handle or a network connection.
In async generators, this .return() method is called automatically, which in turn executes any finally blocks in your generator function.
async function* resourceManager() {
try {
console.log('Acquired resource.');
yield 'Data packet 1';
yield 'Data packet 2';
} finally {
// This will run when the loop finishes, breaks, or has an error.
console.log('Released resource.');
}
}
(async () => {
for await (const data of resourceManager()) {
console.log(data);
if (data === 'Data packet 1') {
break; // Exit early
}
}
})();
// Output:
// Acquired resource.
// Data packet 1
// Released resource.
Notice how "Released resource" is logged even though we broke the loop early. This is a powerful pattern for ensuring resource safety.
Test your understanding!
Given your knowledge of the event loop (macrotasks like setTimeout vs. microtasks from resolved promises), predict the exact output and order of the following code snippet.
async function* generate() {
yield 1;
yield 2;
}
console.log('A: Script start');
setTimeout(() => console.log('B: Timeout!'), 0);
(async () => {
for await (const value of generate()) {
console.log(`C: Loop value ${value}`);
}
})();
Promise.resolve().then(() => console.log('D: Promise resolved'));
console.log('E: Script end');
Show answer
The correct output order is:
A: Script start
E: Script end
D: Promise resolved
C: Loop value 1
C: Loop value 2
B: Timeout!
Explanation:
AandE: The synchronous code runs first, printing "A: Script start" and "E: Script end".setTimeout: ThesetTimeoutcallback (B) is scheduled as a macrotask.for await...of: The async IIFE starts. Thefor await...ofloop callsgenerate().next(). Since an async generator'syieldresolves immediately (likePromise.resolve(1)), it schedules the loop body (C) as a microtask.Promise.resolve(): The.then()callback (D) is also scheduled as a microtask.- Microtask Queue: The main script stack is now empty. The engine processes the microtask queue.
Dwas queued, then the firstCwas queued. So, "D: Promise resolved" prints, followed by "C: Loop value 1". - The loop continues.
next()is called again, and the secondyieldschedules another microtask. The engine immediately runs it, printing "C: Loop value 2". - Macrotask Queue: The microtask queue is now empty. The event loop proceeds to the macrotask queue and executes the
setTimeoutcallback, printing "B: Timeout!".
Conclusion
You've now taken a deep dive into the for await...of loop, moving it from a piece of syntax to a tool you understand fundamentally.
Key Takeaways:
for await...ofis the dedicated syntax for consuming asynchronous iterables—objects that implement the[Symbol.asyncIterator]protocol.- Under the hood, it performs a
whileloop, repeatedly callingawait iterator.next()and checking thedoneproperty of the resolved result. - It processes values sequentially, waiting for each promise to resolve before requesting the next. It does not introduce concurrency.
- It integrates seamlessly with standard JavaScript control flow, including
try...catchfor error handling andbreakfor early termination, which can trigger cleanup logic in the iterator.
Next Up
We've seen how to create and consume asynchronous streams, and how break can stop a for await...of loop from the inside, triggering cleanup. But what if we need to stop an ongoing asynchronous operation from the outside? For example, what if a user navigates away from a page while a large file is being fetched? In the next lesson, we will explore a modern, standard pattern for this exact problem: AbortController and AbortSignal.