Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regarding generator function send() javascript

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?

like image 998
Vino Avatar asked Jan 21 '16 10:01

Vino


People also ask

What are generator functions JavaScript?

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.

What does generator return JavaScript?

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.

What does a generator return?

Simply speaking, a generator is a function that returns an object (iterator) which we can iterate over (one value at a time).


1 Answers

.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());
like image 116
Patrick Evans Avatar answered Oct 08 '22 18:10

Patrick Evans