Created
November 28, 2015 17:15
-
-
Save myshov/33a76c823b6b382f1514 to your computer and use it in GitHub Desktop.
Javascript generator, simple example
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
// Generator can be helpful for linearizing async logic. | |
// It allows you to "pause" code execution with "yield" | |
// and run to the next "yield" or end of generator with "next" | |
function* helloGen() { | |
// 1: 2: | |
var str = yield ' bro'; | |
// 3: | |
console.log(str); | |
} | |
// create iterator | |
var it = helloGen(); | |
// get ' bro' and pause (2) | |
var accost = it.next().value; | |
setTimeout(_ => { | |
// pass into iterator 'hello, bro', that | |
// will be assigned in str (1) and then | |
// will be printed out in the console (3) | |
it.next('hello,' + accost); | |
}, 5000); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment