JavaScript AsyncGenerator

Beginner
9 min read
Updated: Nov 2026
3 examples
Async iteration

Definition and Usage

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.

This page explains the idea. The AsyncGenerator Methods index links the full guides for next(), return() and throw().

One value per step, always through a Promise.

await gen.next() gives you { value, done }. done: true means the generator has finished and will not produce more values.

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
}

Core Ideas

Ideas every AsyncGenerator tutorial in this series builds on:

IdeaExampleRemember
async function*async function* feed() {}Calling it returns an AsyncGenerator object
yieldyield item;Hands out one value and pauses
await insideawait fetchPage(1)Waits for a promise inside the body
next()await gen.next()A Promise of { value, done }
for await...offor await (const x of gen)Reads every value in order

Generator vs Async Function vs Async Generator

Three kinds of functions that look alike but behave differently:

Featurefunction* (generator)async functionasync function*
Calling it returnsA Generator objectOne PromiseAn AsyncGenerator object
How many resultsMany, one at a timeOneMany, one at a time
await insideNoYesYes
next() gives you{ value, done } right awayNo next() methodA Promise of { value, done }
Read it withfor...ofawait 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.

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).

Real-Life Uses

Reach for an async generator whenever data arrives over time and the consumer should handle it piece by piece:

UseWhat the generator does
Paged API dataFetch page 1, 2, 3 and so on, yield the items one by one, and stop at the first empty page.
Streaming lines or chunksTurn raw text chunks from a file or network stream into complete lines for the caller.
PollingCheck a job or server status every few seconds and yield each new state until it is finished.
Progress updatesYield "25%", "50%" and so on while a long task runs, then return the final result.

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();
next() tutorial

How It Works

  1. Wait, then hand out. await fetchPage(page) pauses the generator until the fake request answers; the inner for loop then yields each product separately.
  2. 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.
  3. 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();
return() tutorial

How It Works

  1. Keep the unfinished part. buffer.split("\n") separates complete lines; parts.pop() keeps the last, unfinished piece, so "Ana,3" + "1" becomes Ana,31.
  2. 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.
  3. 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();
Methods index

How It Works

  1. Three requests, no waiting. All three next() calls happen immediately and each returns a pending promise, so "queued" prints before any ticket.
  2. 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.
  3. Matching results. Promise.all keeps the promises in call order, so the values come out as 1, 2, 3.

AsyncGenerator Methods

Every AsyncGenerator object has three methods. Each one returns a Promise and has its own tutorial:

MethodWhat it does
next()Resume the generator; get a Promise of the next { value, done }. next(value) sends a value back in.
return()Finish early; finally blocks run and the promise resolves to { value, done: true }.
throw()Throw an error at the paused yield; the generator can catch it or finish.

Full list: AsyncGenerator Methods index.

Frequently Asked Questions

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.

Browse the AsyncGenerator methods

Open the index for next(), return() and throw(): syntax, runnable examples, and FAQs.

AsyncGenerator Methods index →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

15 people found this page helpful