Ábrahám Endre Ábrahám Endre - 1 month ago 12
Node.js Question

nodejs ES6 generator outputs only {}

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

Answer

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?
Comments