I was viewing generator functions in Mozilla Dev page.
There was an example code which is having send() function.
function* fibonacci() {
var a = yield 1;
yield a * 2;
}
var it = fibonacci();
console.log(it); // "Generator { }"
console.log(it.next()); // 1
console.log(it.send(10)); // 20
console.log(it.close()); // undefined
console.log(it.next()); // throws StopIteration (as the generator is now closed)
But, both chrome and Firefox (Latest version) are throwing error on send() function.
Any views on this? Is it not supported?
A generator is a process that can be paused and resumed and can yield multiple values. A generator in JavaScript consists of a generator function, which returns an iterable Generator object.
A return statement in a generator, when executed, will make the generator finish (i.e. the done property of the object returned by it will be set to true ). If a value is returned, it will be set as the value property of the object returned by the generator.
Simply speaking, a generator is a function that returns an object (iterator) which we can iterate over (one value at a time).
.send
is part of the Legacy generator objects which are specific to the SpiderMonkey engine. It will be removed in some future release. They have already started removing/replacing the legacy generator objects with ES6 generators in parts of their code (Bug 1215846, Bug 1133277)
For the moment you can still use legacy generators in Firefox (current version as of this answer: 43.0.4). Just leave off the *
when defining, and as long as the function body uses a yield
statement the legacy generator will be used.
function fibonacci() {
var a = yield 1;
yield a * 2;
}
var it = fibonacci();
console.log(it);
console.log(it.next());
console.log(it.send(10));
console.log(it.close());
console.log(it.next());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With