The iterators having two optional methods: return(...) and throw(...).
These methods end the sequence in a paused generator as soon as they are called.
function *getFruits() { yield "XML"; yield "Keyboard"; yield "Screen"; } const fruitIterator = getFruits(); console.log(fruitIterator.next()); // {value: 'XML', done: false} console.log(fruitIterator.return("kiwi"));// {value: 'kiwi', done: true} console.log(fruitIterator.next()); // {value: undefined, done: true}
Here, return("kiwi") returns the same value "kiwi" passed as the argument and ends the sequence resulting in done to be true.
This is equivalent to having a return value in the generator function.
Traversing the sequence obtained from a generator does not include the value that signals { done: true }.
The following code are iterating over the collection fruitIterator, which only contains the elements yielded before the return() method was invoked:
function *getFruits() { yield "XML"; yield "Keyboard"; yield "Screen"; return "kiwi"; yield "watermelon"; } const fruitIterator = getFruits(); for (let fruit of fruitIterator) { console.log(fruit); //from w w w . ja va 2 s . c o m }