Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mightyguava/32117e789e3902bd2d1b066d4a113bd1 to your computer and use it in GitHub Desktop.
Save mightyguava/32117e789e3902bd2d1b066d4a113bd1 to your computer and use it in GitHub Desktop.
Demystifying Async Programming in Javascript - Generator internals printer state machine
function printer(start) {
let state = 0;
let done = false;
function go(input) {
let result;
switch (state) {
case 0:
console.log("We are starting!");
state = 1;
break;
case 1:
console.log(input);
state = 2;
break;
case 2:
console.log(input);
state = 3;
break;
case 3:
console.log(input);
console.log("We are done!");
done = true;
state = -1;
break;
default:
break;
return {done: done, value: result};
}
}
return {
next: go
}
}
const counter = printer();
counter.next(1); // We are starting!
counter.next(2); // 2
counter.next(3); // 3
counter.next(4); // 4
counter.next(5); // We are done!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment