An async generator is a function written with async function*. Calling it does not run its body. Instead it returns an AsyncGenerator object that produces values one at a time. Every step is asynchronous: next() returns a Promise that resolves to { value, done }.
Inside the body you can use both await (wait for a promise) and yield (hand one value to the caller and pause). The caller usually reads the values with a for await...of loop.
await gen.next() gives you { value, done }. done: true means the generator has finished and will not produce more values.
Syntax
JavaScript Syntax
Declare the generator with async function*, then read it step by step or with a loop:
JavaScript
async function* numbers() {
const first = await Promise.resolve(1); // await works inside
yield first; // hand out one value
yield Promise.resolve(2); // awaited: the caller gets 2
return "end"; // final result, done: true
}
// inside an async function (or a module):
const gen = numbers(); // the body has not started yet
const step = await gen.next(); // { value: 1, done: false }
for await (const n of numbers()) {
console.log(n); // 1, then 2
}
Reference
Core Ideas
Ideas every AsyncGenerator tutorial in this series builds on:
Idea
Example
Remember
async function*
async function* feed() {}
Calling it returns an AsyncGenerator object
yield
yield item;
Hands out one value and pauses
await inside
await fetchPage(1)
Waits for a promise inside the body
next()
await gen.next()
A Promise of { value, done }
for await...of
for await (const x of gen)
Reads every value in order
Compare
Generator vs Async Function vs Async Generator
Three kinds of functions that look alike but behave differently:
Feature
function* (generator)
async function
async function*
Calling it returns
A Generator object
One Promise
An AsyncGenerator object
How many results
Many, one at a time
One
Many, one at a time
await inside
No
Yes
Yes
next() gives you
{ value, done } right away
No next() method
A Promise of { value, done }
Read it with
for...of
await or .then()
for await...of
A plain generator (function*) is synchronous, so it cannot wait for a network reply between two values. An async function can wait but produces one result. An async generator does both: it waits when it needs to and hands out many values, one per step.
Behavior
How an Async Generator Runs
for await...of
The loop calls next(), awaits the promise, runs its body with value, and stops when done is true. It accepts any object with a Symbol.asyncIterator method; an AsyncGenerator object returns itself from it.
await inside the body
While the generator waits for a promise, only the generator pauses. The rest of the page keeps running; the caller just holds a pending promise from next().
yield of a promise
A yielded promise is awaited before it is handed over, so yield fetchName() gives the caller the name, not a Promise. If it rejects, the error is thrown inside the generator at that yield.
Request queueing
Calls to next() made before the previous one settles never run in parallel: they wait in a queue and are answered in order (Example 3).
Cleanup with try...finally and return()
Put cleanup code in a finally block. It runs when the generator ends, when you call return(), and when a for await...of loop is left with break (Example 2).
Practice
Real-Life Uses
Reach for an async generator whenever data arrives over time and the consumer should handle it piece by piece:
Use
What the generator does
Paged API data
Fetch page 1, 2, 3 and so on, yield the items one by one, and stop at the first empty page.
Streaming lines or chunks
Turn raw text chunks from a file or network stream into complete lines for the caller.
Polling
Check a job or server status every few seconds and yield each new state until it is finished.
Progress updates
Yield "25%", "50%" and so on while a long task runs, then return the final result.
Code
JavaScript Examples
Three short programs that show async generators doing real work. Each one only prints plain text, so the output is the same in Node.js and in the browser console.
Example 1 — Read a Paged API with for await...of
A fake fetchPage(n) returns a promise of an array. The generator walks the pages and yields one product at a time.
JavaScript
const fakeApi = { 1: ["apple", "banana"], 2: ["cherry"], 3: [] };
function fetchPage(page) {
return new Promise((resolve) => {
setTimeout(() => resolve(fakeApi[page]), 5);
});
}
async function* allProducts() {
let page = 1;
while (true) {
const items = await fetchPage(page);
if (items.length === 0) break;
console.log("-- page " + page + " loaded");
for (const item of items) {
yield item;
}
page++;
}
yield Promise.resolve("(end of catalog)");
}
async function run() {
for await (const product of allProducts()) {
console.log(product);
}
}
run();
-- page 1 loaded
apple
banana
-- page 2 loaded
cherry
(end of catalog)
How It Works
Wait, then hand out.await fetchPage(page) pauses the generator until the fake request answers; the inner for loop then yields each product separately.
Lazy loading. Page 2 is only requested after the loop has consumed "apple" and "banana", which is why the "page 2 loaded" line appears between the products.
Yielded promises are unwrapped. The last yield hands over a promise, yet the loop prints the plain text (end of catalog), because async generators await what they yield.
Example 2 — Turn Chunks into Lines and Stop Early
Text arrives in uneven chunks, like a network stream. One generator splits it into lines; leaving the loop at "END" cleans up both generators.
JavaScript
async function* readChunks() {
const chunks = ["name,age\nAna,3", "1\nBen,25\nEN", "D\nCara,40"];
try {
for (const chunk of chunks) {
await Promise.resolve(); // pretend to wait for the network
yield chunk;
}
} finally {
console.log("file closed");
}
}
async function* readLines(source) {
let buffer = "";
for await (const chunk of source) {
buffer += chunk;
const parts = buffer.split("\n");
buffer = parts.pop();
for (const line of parts) {
yield line;
}
}
if (buffer !== "") yield buffer;
}
async function run() {
for await (const line of readLines(readChunks())) {
if (line === "END") break;
console.log("line: " + line);
}
console.log("done reading");
}
run();
Keep the unfinished part.buffer.split("\n") separates complete lines; parts.pop() keeps the last, unfinished piece, so "Ana,3" + "1" becomes Ana,31.
Generators in a chain.readLines consumes readChunks with its own for await...of, so each line is produced only when the outer loop asks for it.
Cleanup travels down the chain.break at "END" calls return() on readLines, which closes its own loop and, in turn, the finally in readChunks prints "file closed".
Example 3 — Calls to next() Are Queued
Ask for three tickets at once without waiting. The generator still issues them one after another, in order.
JavaScript
async function* tickets() {
for (let number = 1; number <= 3; number++) {
await new Promise((resolve) => setTimeout(resolve, 5));
console.log("issuing ticket " + number);
yield number;
}
}
async function run() {
const counter = tickets();
const first = counter.next();
const second = counter.next();
const third = counter.next();
console.log("three next() calls queued");
const results = await Promise.all([first, second, third]);
console.log(results.map((r) => r.value).join(", "));
}
run();
Three requests, no waiting. All three next() calls happen immediately and each returns a pending promise, so "queued" prints before any ticket.
Served one by one. The generator handles the first request, pauses at yield, and only then starts the second: the tickets are issued in order, never in parallel.
Matching results.Promise.all keeps the promises in call order, so the values come out as 1, 2, 3.
Continue
AsyncGenerator Methods
Every AsyncGenerator object has three methods. Each one returns a Promise and has its own tutorial:
The object you get when you call an async generator function (async function*). It produces values one at a time; each next() call returns a Promise of { value, done }. You usually read it with for await...of.
A normal generator (function*) is synchronous: next() returns { value, done } at once and the body cannot await. An async generator can await between values, and its next(), return() and throw() return Promises.
An async function returns one Promise for one result. An async generator delivers many results over time, one per next() call, pausing at each yield until the caller asks for more.
The call is queued. An async generator never runs two steps at once: it finishes the current step, then answers queued calls in the order they were made.
Put cleanup code in a finally block inside the generator, then break out of the for await...of loop or call return(). Both finish the generator and run the finally block before the promise settles.