Consuming Async Generators with for-await-of
You'll learn how to use for-await-of loops to cleanly iterate through async generator values.
The Perfect Partnership
Now that you know how to create async generators (functions that yield promises or async values), you need an elegant way to consume them. That's exactly what for-await-of was designed for! This loop automatically handles the asynchronous iteration protocol, awaiting each yielded promise and giving you clean, sequential access to values.
How It Works
When you use for-await-of with an async generator:
- The loop calls the generator's
next()method - It awaits the resulting promise
- It extracts the
valuefrom the resolved{value, done}object - It assigns that value to your loop variable
- It repeats until
doneistrue
All this complexity is hidden behind simple, readable syntax:
async function* countWithDelay() {
yield Promise.resolve(1);
yield Promise.resolve(2);
yield Promise.resolve(3);
}
async function consume() {
for await (const num of countWithDelay()) {
console.log(num); // 1, then 2, then 3
}
console.log('Done!');
}
consume();
Why This Matters
Without for-await-of, you'd need to manually call .next(), await each promise, check the done flag, and handle the unwrapping yourself—messy and error-prone. The for-await-of loop makes consuming async sequences as natural as iterating an array.
Think of it like a conveyor belt that automatically waits for each package to arrive before handing it to you, rather than dumping everything at once.
Key Takeaway: for-await-of is the clean, idiomatic way to consume async generators, automatically handling promise resolution and iteration protocol details so you can focus on processing the values.