Two-Way Communication: Yielding Out and Receiving In
You'll learn how generators create a bidirectional conversation between the generator function and its caller.
The Two-Way Street
Until now, you've seen yield send values out to the caller, and next() pass values in to the generator. But here's the magic: these happen simultaneously in opposite directions. When you call next(value), that value becomes the result of the last yield expression inside the generator, while the generator simultaneously yields a new value back out.
Think of it like a relay race: the generator hands off a baton (yields a value), pauses, then when the caller passes back a new baton (via next(value)), the generator catches it where it paused and continues running.
How It Works
function* conversation() {
const answer1 = yield "What's your name?";
console.log(`You said: ${answer1}`);
const answer2 = yield "What's your favorite color?";
console.log(`You said: ${answer2}`);
return "Thanks!";
}
const chat = conversation();
console.log(chat.next().value); // "What's your name?"
console.log(chat.next("Alice").value); // Logs "You said: Alice", yields "What's your favorite color?"
console.log(chat.next("Blue").value); // Logs "You said: Blue", returns "Thanks!"
The first next() starts the generator, which yields the first question. The second next("Alice") sends "Alice" back into the generator (it becomes the value of answer1), and the generator continues to yield the next question. This ping-pong continues until the generator completes.
Key Takeaway: Generators enable two-way communication where yield sends values to the caller while next(value) sends values back into the generator, creating a powerful back-and-forth dialogue.