Multiple Yields in Sequence
You'll learn how generators can pause and resume multiple times by using several yield statements in order.
The Core Idea
So far you've seen generators with a single yield. But the real power comes from using multiple yields in the same generator function. Each time you call next(), execution resumes from the last yield and continues until it hits the next one. It's like having multiple pause points in your function.
Think of it like a tour guide walking a group through a museum: "Here's exhibit one [pause], now let's see exhibit two [pause], and finally exhibit three [done]." Each pause is a yield, and the tour only continues when the group says "next."
How It Works
function* multipleStops() {
yield 'First stop';
yield 'Second stop';
yield 'Third stop';
}
const tour = multipleStops();
console.log(tour.next()); // { value: 'First stop', done: false }
console.log(tour.next()); // { value: 'Second stop', done: false }
console.log(tour.next()); // { value: 'Third stop', done: false }
console.log(tour.next()); // { value: undefined, done: true }
Each yield statement pauses execution and returns a value. The generator "remembers" where it left off, including any local variables. When you call next() again, it picks up right after the previous yield and runs until the next one.
function* counter() {
yield 1;
yield 2;
yield 3;
}
for (const num of counter()) {
console.log(num); // 1, 2, 3
}
Key Takeaway: Generators can have multiple yield statements that execute in sequence, pausing and resuming execution each time next() is called, making them perfect for producing a series of values over time.