37
loading...
This website collects cookies to deliver better user experience
function* tacoIngredients() {
yield 'Shell';
yield 'Meat';
yield 'Lettuce';
yield 'Cheese';
}
function*
syntax.yield
keyword in the example above. When a generator function is called, it executes until it encounters a yield
expression. At this point, the generator function pauses, returns the value defined after the yield
keyword, and waits to continue execution until the function is called again.{
value, // the next value you want to get from the generator function
done; // a flag informing you if this is the last value in the sequence
}
tacoIngredients
function defined in the example above, it would look something like this:function* tacoIngredients() {
yield 'Shell';
yield 'Meat';
yield 'Lettuce';
yield 'Cheese';
}
const taco = tacoIngredients();
console.log(taco.next()); // { value: 'Shell', done: false }
next()
method, an object is returned in the shape mentioned prior. To get the data, simply access the value
property. Because the done
property has a value of false, we know there is more data to be retrieved and we can call the generator again.function* tacoIngredients() {
yield 'Shell';
yield 'Meat';
yield 'Lettuce';
yield 'Cheese';
}
const taco = tacoIngredients();
console.log(taco.next()); // { value: 'Shell', done: false }
console.log(taco.next()); // { value: 'Meat', done: false }
console.log(taco.next()); // { value: 'Lettuce', done: false }
console.log(taco.next()); // { value: 'Cheese', done: false }
console.log(taco.next()); // { done: true }
next()
after the generator has encountered its last yield
keyword, it returns an object with a single property - and it's probably what you're expecting - done
is set to true!