Getting return value from generator in Node JS

I can't figure out how to get the return value of the generator - does anyone know what I'm 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. To run this code, you will need node 0.11.12 with the --harmony option.

+4
source share
3 answers

When currentNext.done true, curentNext.valuehas a return value.

You can write your loop as:

var next;
while (!(next = generator.next()).done) {
    var yieldedValue = next.value;
}
var returnValue = next.value;
+11
source

It seems to work by passing the current value back to the generator when I call .next:

function getGeneratorReturn() {
    var generator = runGenerator();
    var generatorReturn = null;

    var done = false;
    while(!done) {
        var currentNext = generator.next(generatorReturn);
        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. To run this code, you will need node 0.11.12 with the --harmony option.

+1
source

CAN NOT return . Iterator, .

Since the generator function is always executed asynchronously (initiated by operators yieldor even by manually entering values ​​using Iterator.next( value)- see this example ), the operator returncan only be used to "close" the Iteratorgenerator function returned in your code.

You can only "return" values ​​from a generator function with yield.

-2
source

Source: https://habr.com/ru/post/1538933/


All Articles