Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Demystifying Async Programming in Javascript - Generator internals counts state machine
function counts(start) {
let state = 0;
let done = false;
function go() {
let result;
switch (state) {
case 0:
result = start + 1;
state = 1;
break;
case 1:
result = start + 2;
state = 2;
break;
case 2:
result = start + 3;
state = 3;
break;
case 3:
result = start + 4;
done = true;
state = -1;
break;
default:
break;
}
return {done: done, value: result};
}
return {
next: go
}
}
const counter = counts(0);
console.log(counter.next()); // {value: 1, done: false}
console.log(counter.next()); // {value: 2, done: false}
console.log(counter.next()); // {value: 3, done: false}
console.log(counter.next()); // {value: 4, done: true}
console.log(counter.next()); // {value: undefined, done: true}
@russfrisch

This comment has been minimized.

Copy link

russfrisch commented Mar 24, 2017

I'm currently reading through the blog where this code snippet is presented and just have a quick question: Given that this is an example of how to build a generator using ES5, shouldn't the the lets be vars?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.