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

Async Generator Return Values

Understand how return statements in async generators work and affect the iterator result object.

Async Generator Return Values

You'll learn how return statements in async generators affect the final iterator result and signal completion.

The Core Idea

When you use a return statement inside an async generator, it terminates the generator and produces a special iterator result object with done: true and a value property containing whatever you returned. This is different from yield, which produces values but keeps the generator alive.

Think of it like ending a conversation: yield is saying "here's something for you, I'll wait for your response," while return is saying "here's my final word, goodbye."

How It Works

async function* countWithFarewell() {
  yield 1;
  yield 2;
  return "That's all!"; // Terminates the generator
}

(async () => {
  const gen = countWithFarewell();
  
  console.log(await gen.next()); // { value: 1, done: false }
  console.log(await gen.next()); // { value: 2, done: false }
  console.log(await gen.next()); // { value: "That's all!", done: true }
  console.log(await gen.next()); // { value: undefined, done: true }
})();

The Catch with For-Await-Of

Here's something important: for-await-of loops ignore the return value. They only process yielded values and stop when done: true appears.

async function* numbers() {
  yield 10;
  yield 20;
  return 999; // Won't appear in the loop
}

for await (const num of numbers()) {
  console.log(num); // Prints: 10, 20 (999 never shows)
}

To capture the return value, you must manually call .next() and check the result object.

Key Takeaway: Return statements in async generators set done: true and provide a final value in the iterator result object, but that value is invisible to for-await-of loops—use manual .next() calls if you need it.