What Are Async Generators?
You'll learn how async generators elegantly merge generator functions with async/await to produce values over time asynchronously.
The Core Idea
An async generator is a special function that combines two powerful features you already know:
- Generator functions (using
function*) that yield multiple values and pause execution - Async/await for handling asynchronous operations
Think of it like a factory assembly line that not only pauses between producing items (generator behavior) but also waits for materials to arrive asynchronously before making each item (async behavior).
Syntax and Structure
Async generators use both the async keyword and the * asterisk:
async function* myAsyncGenerator() {
yield await fetchData(1);
yield await fetchData(2);
yield await fetchData(3);
}
Notice how it combines async function* — this creates a function that returns an async iterable when called.
What You Get Back
When you call an async generator, you receive an object that implements Symbol.asyncIterator. This means you can use it with for-await-of:
async function* countWithDelays() {
yield await Promise.resolve(1);
yield await Promise.resolve(2);
yield await Promise.resolve(3);
}
for await (const num of countWithDelays()) {
console.log(num); // 1, then 2, then 3
}
Each yield can await a promise before producing the next value, giving you sequential asynchronous value production.
Why This Matters
Async generators shine when you need to produce a sequence of values where each value requires an async operation — like paginating through API results, processing a stream of database records, or reading files one at a time.
Key Takeaway: Async generators (async function*) combine generators with async/await, letting you yield asynchronous values in sequence and making them iterable with for-await-of.