Next Method in JavaScript Generators
The next method is a fundamental part of working with JavaScript generators. It allows us to control the execution of a generator function, retrieve values yielded by the generator, and even send data back into the generator. This page explores the next method through examples, listings, and figures to illustrate its usage and capabilities.
Basic Usage of the next Method
When a generator function is invoked, it returns an iterator object. This iterator has a next method that, when called, resumes the execution of the generator function until the next yield expression is encountered. The next method returns an object with two properties: value and done. The value property contains the yielded value, and the done property is a boolean indicating whether the generator has completed its execution.
Example
function* generatorFunction() {
yield 1;
yield 2;
}
const iterator = generatorFunction();
console.log(iterator.next()); // { value: 1, done: false }
console.log(iterator.next()); // { value: 2, done: false }
console.log(iterator.next()); // { value: undefined, done: true }
In this example, the generatorFunction yields two values, 1 and 2. Each call to next retrieves the next value, and the final call indicates that the generator is done.
Controlling a Generator
The next method can be used to control the flow of a generator. By calling next, we can step through the generator's execution and retrieve each yielded value.
Listing 6.2: Controlling a Generator through an Iterator Object
function* WeaponGenerator(){
yield "Katana";
yield "Wakizashi";
}
const weaponsIterator = WeaponGenerator();
const result1 = weaponsIterator.next();
assert(typeof result1 === "object"
&& result1.value === "Katana"
&& !result1.done,
"Katana received!");
const result2 = weaponsIterator.next();
assert(typeof result2 === "object"
&& result2.value === "Wakizashi"
&& !result2.done,
"Wakizashi received!");
const result3 = weaponsIterator.next();
assert(typeof result3 === "object"
&& result3.value === undefined
&& result3.done,
"There are no more results!");
In this listing, the WeaponGenerator yields two weapon names. The next method is used to retrieve each weapon, and assertions are made to verify the values and the completion status of the generator.
Sending Data to a Generator
In addition to retrieving values, the next method can also send data into a generator. This is done by passing an argument to next, which becomes the value of the current yield expression.
Listing 6.8: Sending Data to and Receiving Data from a Generator
function* NinjaGenerator(action) {
const imposter = yield ("Hattori " + action);
assert(imposter === "Hanzo",
"The generator has been infiltrated");
yield ("Yoshi (" + imposter + ") " + action);
}
const ninjaIterator = NinjaGenerator("skulk");
const result1 = ninjaIterator.next();
assert(result1.value === "Hattori skulk", "Hattori is skulking");
const result2 = ninjaIterator.next("Hanzo");
assert(result2.value === "Yoshi (Hanzo) skulk",
"We have an imposter!");
In this example, the generator NinjaGenerator receives an initial argument action and yields a value based on it. The next method is then used to send the value "Hanzo" back into the generator, which is used in the subsequent yield expression.
Throwing Exceptions to Generators
Generators can also handle exceptions thrown into them using the throw method of the iterator. This allows for more complex control flows and error handling within generator functions.
Listing 6.9: Throwing Exceptions to Generators
function* NinjaGenerator() {
try{
yield "Hattori";
fail("The expected exception didn't occur");
}
catch(e){
assert(e === "Catch this!", "Aha! We caught an exception");
}
}
const ninjaIterator = NinjaGenerator();
const result1 = ninjaIterator.next();
assert(result1.value === "Hattori", "We got Hattori");
ninjaIterator.throw("Catch this!");
In this listing, the generator NinjaGenerator is designed to catch an exception thrown into it. The throw method is used to send the exception, which is then caught and handled within the generator.
Visualizing the next Method
The process of sending data into a generator using the next method is visually represented in Figure 6.3.
Figure 6.3. The first call to ninjaIterator.next() requests a new value from the generator, which returns Hattori skulk and suspends the execution of the generator at the yield expression. The second call to ninjaIterator.next("Hanzo") requests a new value, but also sends the argument Hanzo into the generator. This value will be used as the value of the whole yield expression, and the variable imposter will now carry the value Hanzo.
This figure illustrates how the next method not only retrieves values but can also pass data back into the generator, affecting its subsequent execution.