I can't seem to figure out how to get at the return value of a generator - anyone know what I am doing wrong?
function getGeneratorReturn() {
var generator = runGenerator();
var generatorReturn = null;
var done = false;
while(!done) {
var currentNext = generator.next();
console.log('Current next:', currentNext);
generatorReturn = currentNext.value;
done = currentNext.done;
}
return generatorReturn;
}
function* runGenerator() {
var a = yield 1;
var b = yield 2;
var c = a + b;
return c;
}
var generatorReturn = getGeneratorReturn();
console.log(generatorReturn); // Should output 3, is outputting NaN
Note: You'll need node 0.11.12 running with the --harmony option for this code to run.
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.
Simply speaking, a generator is a function that returns an object (iterator) which we can iterate over (one value at a time).
Calling a generator function inside another to generate a function: we can call a generator function inside another generator function by using the yield * operator (or statement). Example 3: In this example, we call a generator function inside another generator function using the yield * statement.
An iterator (like the one you're creating when you call a generator function) has one property for getting the next value: next . next is a method that continues the generator until the next yield or return, and returns whatever value is yielded or returned in an object.
When currentNext.done
is true
, curentNext.value
has the return value.
You can write your loop as:
var next;
while (!(next = generator.next()).done) {
var yieldedValue = next.value;
}
var returnValue = next.value;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With