Created
August 23, 2017 17:38
-
-
Save leovolving/694e23271402be33c0fdb2e3d91f4d09 to your computer and use it in GitHub Desktop.
Basic JS Generator
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
//I typically use promise chains to handle | |
//sync control but today I'm playing around with generators. | |
//View on Repl: https://repl.it/KWdA/1 | |
function *myGen() { | |
var one = yield 1; | |
var two = yield 2; | |
var three = yield 3; | |
console.log(one, two, three); | |
} | |
const gen = myGen(); | |
//first yielded value | |
console.log(gen.next()); | |
//second yielded value | |
console.log(gen.next()); | |
//third yielded value | |
console.log(gen.next()); | |
//Runs console.log on line 5 | |
//Now that generator has completed | |
//Value undefined because there are no more | |
//yielded values. Done = true | |
console.log(gen.next()); | |
//console.log on line 5 returned all undefined values | |
//because no values were returned above. Let's | |
//fix that. | |
const gen2 = myGen(); | |
console.log(gen2.next()); | |
console.log(gen2.next(1)); | |
console.log(gen2.next(2)); | |
console.log(gen2.next(3)); | |
//values given back to generator aren't | |
//required to be the same as values yielded | |
const gen3 = myGen(); | |
console.log(gen3.next()); | |
console.log(gen3.next('foo')); | |
console.log(gen3.next(false)); | |
console.log(gen3.next({foo: 'bar'})); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment