Last active
August 29, 2015 13:56
-
-
Save matthewmueller/9160537 to your computer and use it in GitHub Desktop.
understanding generators
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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