Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the return value from a generator in Node JS

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.

like image 273
Kirk Ouimet Avatar asked May 01 '14 23:05

Kirk Ouimet


People also ask

Can a generator return a value?

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.

What does the generator return?

Simply speaking, a generator is a function that returns an object (iterator) which we can iterate over (one value at a time).

How do you call a function from a normal generator?

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.

How do you supply data to an already running generator?

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.


1 Answers

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;
like image 87
Felix Kling Avatar answered Oct 13 '22 06:10

Felix Kling