Skip to content

Instantly share code, notes, and snippets.

@matthewmueller
Last active August 29, 2015 13:56
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 matthewmueller/9160537 to your computer and use it in GitHub Desktop.
Save matthewmueller/9160537 to your computer and use it in GitHub Desktop.
understanding generators
/**
* Excerpt from: Analysis of generators and other async patterns in node
* URL: http://spion.github.io/posts/analysis-generators-and-other-async-patterns-node.html#a-gentle-introduction-to-generators
*
* When next is invoked, it starts the execution
* of the generator. The generator runs until it
* encounters a yield expression. Then it pauses
* and the execution goes back to the code that
* called next.
* So in a way, yield works similarly to return.
* But there is a big difference. If we call next
* on the generator again, the generator will
* resume from the point where it left off -
* from the last yield line.
*/
function *something(msg) {
msg += yield msg; // yields "a", returns "b"
msg += yield msg; // yields "ab", returns "c"
msg += yield msg; // yields "abc", returns "d"
return msg; // returns "abcd"
}
var gen = something('a');
console.log(gen.next().value); // a
console.log(gen.next('b').value); // ab
console.log(gen.next('c').value); // abc
console.log(gen.next('d').value); // abcd
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment