-2

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

Ábrahám Endre
  • 519
  • 4
  • 12
  • Possible duplicate of [What are ES6 generators and how can I use them in node.js?](http://stackoverflow.com/q/18842105/1529630) or [What is “function*” in JavaScript?](http://stackoverflow.com/q/9620586/1529630) – Oriol Oct 26 '16 at 20:24

2 Answers2

3

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?
Shanoor
  • 11,466
  • 2
  • 23
  • 37
0

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.

Denis Lisitskiy
  • 1,127
  • 9
  • 13