Skip to content

Instantly share code, notes, and snippets.

@matthewmueller matthewmueller/gen.js
Last active Aug 29, 2015

Embed
What would you like to do?
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
You can’t perform that action at this time.