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

Yielding Promises in Async Generators

Explore how yield in async generators automatically wraps values in promises and handles awaited values.

Yielding Promises in Async Generators

What you'll learn: How yield in async generators automatically handles promises and awaited values for you.

The Magic of Yield in Async Generators

In an async generator, the yield keyword does something beautifully convenient: it automatically wraps whatever you yield in a promise. This means you can yield raw values, already-resolved promises, or pending promises, and the async generator protocol handles everything consistently.

When you yield a value inside an async function*, that value gets packaged into a promise and becomes part of the { value, done } iterator result. For consumers using for-await-of or manually calling next(), this means every yielded item arrives as an awaited, resolved value—no extra work needed.

How It Works

Think of yield in an async generator like a conveyor belt that automatically gift-wraps items. Whether you hand it a toy, a pre-wrapped box, or a promise to deliver something later, it ensures everything comes out wrapped uniformly for the recipient.

async function* mixedYields() {
  yield 1;                          // Plain value → wrapped in promise
  yield Promise.resolve(2);         // Already a promise → awaited
  yield await fetch('/data');       // Awaited value → re-wrapped
}

(async () => {
  for await (const value of mixedYields()) {
    console.log(value); // 1, 2, [response object]
  }
})();

All three yields produce the same structure: a promise containing the value. The for-await-of loop unwraps each automatically.

Key Takeaway: In async generators, yield automatically wraps all values in promises and ensures awaited resolution, making promise handling seamless for both the generator author and consumer.