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

The next() Method with Async Generators

Explore how calling next() on an async generator returns a promise that resolves to an iterator result.

The next() Method with Async Generators

You'll learn how calling next() on an async generator returns a promise that resolves to an iterator result object.

Understanding next() with Async Generators

When you call next() on a regular generator, you immediately get back an iterator result object ({ value, done }). With async generators, there's an important difference: calling next() returns a promise that resolves to that iterator result object.

Think of it like ordering food for delivery versus picking it up at a counter. A regular generator hands you the result instantly (counter pickup). An async generator gives you a promise—a receipt that eventually delivers your result when it's ready.

How It Works

async function* asyncCounter() {
  yield 1;
  yield 2;
  yield 3;
}

const gen = asyncCounter();

// Calling next() returns a Promise
const promise1 = gen.next();
console.log(promise1); // Promise { <pending> }

// Await the promise to get the iterator result
promise1.then(result => {
  console.log(result); // { value: 1, done: false }
});

// Or use await
(async () => {
  const result2 = await gen.next();
  console.log(result2); // { value: 2, done: false }
  
  const result3 = await gen.next();
  console.log(result3); // { value: 3, done: false }
  
  const result4 = await gen.next();
  console.log(result4); // { value: undefined, done: true }
})();

The promise layer exists because the async generator might need to perform asynchronous operations before producing each value. You must await or use .then() to access the actual iterator result.

Key Takeaway: Calling next() on an async generator always returns a promise that resolves to { value, done }, requiring you to await or handle the promise before accessing the iteration result.