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

Passing Values into Async Generators

Learn how to send values into async generators using the next() method's argument parameter.

Passing Values into Async Generators

You'll learn how to send data into a running async generator from the outside using the next() method's argument.

The Two-Way Street

You already know that async generators produce values with yield and you consume them by calling next(). But here's the twist: the next() method can also accept an argument, and that argument becomes the result of the yield expression inside the generator. It's a two-way conversation—the generator yields values out, and the consumer can send values back in.

Think of it like a back-and-forth negotiation: the generator pauses at yield and waits. When you call next(someValue), that value gets "injected" right where the generator paused, replacing the yield expression.

How It Works

async function* twoWayGenerator() {
  const first = yield "What's your name?";
  console.log(`Received: ${first}`);
  
  const second = yield "What's your age?";
  console.log(`Received: ${second}`);
}

const gen = twoWayGenerator();

await gen.next();           // First call starts generator
await gen.next("Alice");    // "Alice" becomes value of first yield
await gen.next(30);         // 30 becomes value of second yield

Important: The first next() call starts the generator—there's no yield to receive a value yet. Starting with the second next() call, your argument gets passed into the most recent yield.

Common Pattern

This is useful for generators that need external input to decide what to yield next, like interactive workflows or state machines that respond to feedback.

Key Takeaway: Use next(value) to pass data into an async generator, where it becomes the result of the paused yield expression—enabling true bidirectional communication.