Reputation: 21007
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.
Upvotes: 0
Views: 532
Reputation: 664936
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.
Upvotes: 1