var x = 1
// define a generator
function *foo() {
x++;
yield; // pause
console.log("x: ", x);
}
// just an ordinary function that increments x
function bar() {
x++;
}
// create the iterator object to control the generator
var it = foo()
// run the generator until the first yield (or the end of the function if there is no yield)
it.next(); // start foo here
// note that it.next at this point returns {value: undefined, done: false}
// value is undefined because our generator is not returning anything
// at this point we check the value of x, which is incremented by 1 as expected
x; // 2
// while the generator is paused, incrememnt x again
bar();
// continue running the generator (unpause) until the end (or until the next yield statement)
it.next();
// note that it.next at this point returns {value: undefined, done: true}
// x is logged to the console and it is incremented by 2. this is amazing :-D
x: 3
Last active
June 12, 2018 12:16
-
-
Save amysimmons/52a44ab6abc5f6354b02837e8e1da398 to your computer and use it in GitHub Desktop.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment