Course contentsShow
← JavaScript
Lesson 2039 of 2,72342. Iteration Protocols Deep DiveFree lesson

Async Generator Syntax

Understand the async function* syntax and how it differs from regular generators and async functions.

Async Generator Syntax

What you'll learn: How to write async generator functions using the async function* syntax and what makes them unique.

The Special Combination

An async generator combines two powerful features: the async keyword (for handling promises) and the function* syntax (for yielding multiple values). The result is async function* — a function that can both yield values and await promises.

async function* fetchUserPages() {
  let page = 1;
  while (page <= 3) {
    await new Promise(resolve => setTimeout(resolve, 1000));
    yield `Page ${page} data`;
    page++;
  }
}

How It Differs from Regular Generators

A regular generator (function*) yields values synchronously and returns an iterator. You can't use await inside it:

function* regularGen() {
  yield 1;
  yield 2;
  // await something; // ❌ Not allowed!
}

How It Differs from Async Functions

A regular async function (async function) can await promises but can only return a single value wrapped in a promise. It can't yield multiple values:

async function regularAsync() {
  await something;
  return "one value"; // Only one result
  // yield "multiple"; // ❌ Not allowed!
}

The Unique Power of Async Generators

With async function*, you get both abilities:

async function* streamData() {
  yield await fetchFirst();  // ✅ await AND yield
  yield await fetchSecond(); // ✅ Can do this multiple times
}

The function returns an async iterator that you can consume with for-await-of or by manually calling .next(), which returns a promise.

Key Takeaway: The async function* syntax creates async generators that can both await promises and yield multiple values over time, combining the powers of regular generators and async functions into one tool for handling asynchronous sequences.