Multiple Yields in Sequence
You'll learn how generator functions can yield multiple values one after another, and how they're delivered in order during iteration.
The Core Idea
When a generator function contains multiple yield statements, each call to next() resumes execution from where it last paused and runs until hitting the next yield. This creates a sequence of values delivered one at a time, maintaining perfect order.
Think of it like a ticket dispenser at a deli counter: each time someone presses the button (calls next()), the machine dispenses the next number in sequence, then waits. The numbers come out in perfect order, one per press.
How It Works
function* countToThree() {
yield 1;
yield 2;
yield 3;
}
const counter = countToThree();
console.log(counter.next()); // { value: 1, done: false }
console.log(counter.next()); // { value: 2, done: false }
console.log(counter.next()); // { value: 3, done: false }
console.log(counter.next()); // { value: undefined, done: true }
Each yield acts as a checkpoint. The generator pauses there, returns the yielded value, and waits. When next() is called again, it picks up right after the previous yield and continues until the next one.
Natural Iteration
Since generators implement the iterator protocol, for...of automatically calls next() repeatedly:
function* greetings() {
yield "Hello";
yield "Bonjour";
yield "Hola";
}
for (const greeting of greetings()) {
console.log(greeting); // "Hello", then "Bonjour", then "Hola"
}
Key Takeaway: Multiple yield statements in a generator create an ordered sequence of values, with each call to next() advancing to the next yield in the function body.