简体   繁体   中英

Generators and babel-node

Not sure if it is my ES6 inexperience of something wrong with using Babel, but I am trying to create a sort of asynchronous if ... then

var token = 6;

var f1 = function*() {
    if (token > 5) {
        getToken();
        token = yield;
    }
    console.log(token);
};

var getToken  = function() {
    for (i=0; i<10000000; i++) {
        var x = i*2;
    }
    f1(0);
};

f1();

which I then run from its file with

babel-node generator.es6.js

I am expecting 0 but I don't get anything at all.

You need to call generator functions to create a generator, and then advance that using .next() calls:

function* f() {
    var token = 6;
    if (token > 5) {
        getToken();
        token = yield;
    }
    console.log(token);
};

function getToken() {
    setTimeout(function() {
        f1.next(0); // advance generator
    }, 100);
};

var f1 = f(); // create generator
f1.next(); // start generator

Notice that advancing the generator must be done asynchronously, calling it directly from getToken would have resulted in a TypeError from f1.next() while f1 was still executing. It needs to reach the yield statement first.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM