I am experimenting with ES6 generator functions and output operators, Example .
function run(generator) {
var itr = generator(resume);
function resume(callbackValue) {
itr.next(callbackValue);
}
itr.next();
}
function* main(resume) {
var result1 = yield add(1, resume);
var data1 = result1;
console.log("add 1 = ", data1)
var data2 = yield add(1, resume);
console.log("add 1 = ", data2);
var data3 = yield add(data1, resume);
console.log("add data1 =", data3);
console.log("total is ", data1 + data2 + data3);
}
function add(num, resume) {
setTimeout(function() {
resume(num + 1);
}, 0);
}
run(main);
I plan to use the output as a flow control for asynchronous REST calls, where the request will be called next after the answer, but for now I just use a simple add. It works as planned, which is interesting, but renewal will only work in setTimeout, and I'm not sure why. If it is simple:
function add (num, resume) {
resume(num + 1);
}
the interpreter gives me "The generator is already running."
No need to be a real wait during a timeout, and I also tried the self invoking function, but that didn't help. Why do I itr.next()
need a timeout?