-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

asked Apr 3, 2016 at 17:16
1

2 Answers 2

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?
answered Apr 3, 2016 at 17:22
Sign up to request clarification or add additional context in comments.

Comments

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.

answered Oct 26, 2016 at 19:48

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.