The following codes only output {} no matter what I do to my generator functions:
//test 1
function *myFunc(input) {
//yield input;
return input;
}
console.log(myFunc('dafuq happening')); //prints {}
//test 2
function *myFunc2() {
console.log('wtf?');
}
myFunc2(); //prints {}
using nodeJS 5.10 on arch linux
asked Apr 3, 2016 at 17:16
Ábrahám Endre
6871 gold badge6 silver badges12 bronze badges
-
Possible duplicate of What are ES6 generators and how can I use them in node.js? or What is "function*" in JavaScript?Oriol– Oriol2016年10月26日 20:24:59 +00:00Commented Oct 26, 2016 at 20:24
2 Answers 2
Calling the function only return an instance of Generator, it doesn't run the content of the function yet. You have to call next() on the instance to start pulling the values:
//test 1
function *myFunc(input) {
//yield input;
return input;
}
console.log(myFunc('dafuq happening').next());
// prints { value: 'dafuq happening', done: true }
//test 2
function *myFunc2() {
console.log('wtf?');
}
myFunc2().next();
// prints wtf?
answered Apr 3, 2016 at 17:22
Shanoor
13.7k2 gold badges32 silver badges41 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
For controlling a flow of generator, I prefer (recommend) to use lib co
var co = require('co');
co(myFunc())
.then(function(result){
//Value, returned by generetor, on finish
})
.catch(function(error){
//I recimmend always finish chain by catch. Or you can loose errors
console.log(error);
})
And remember, that you have to yield only function, promise, generator, array, or object.
answered Oct 26, 2016 at 19:48
Denis Lisitskiy
1,34311 silver badges15 bronze badges
Comments
lang-js