Created
April 13, 2017 01:46
-
-
Save PantherHawk/87e559239ea66fdae2e43821be3d4792 to your computer and use it in GitHub Desktop.
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
//Generators | |
// Remember functions? | |
function doA() { | |
console.log('did A'); | |
} | |
function doB() { | |
console.log('did B') | |
} | |
function justAFxn() { | |
doA(); | |
doB() | |
} | |
justAFxn() | |
//Yielding values | |
var helloWorld = function*() { | |
yield 'hello'; | |
yield 'world'; | |
} | |
var gen = helloWorld(); | |
var a = gen.next(); | |
console.log('from a we get: \n', a); | |
var b = gen.next(); | |
console.log('from b we get: \n', b); | |
//Feeding values | |
var c = gen.next(); | |
console.log('from c we get: \n', c) | |
var d = gen.next() | |
console.log(d) | |
//Feeding values | |
var ohHai = function*() { | |
var x = yield 'hello'; | |
yield x + ' world'; | |
} | |
var gen = ohHai(); | |
var a = gen.next(); | |
console.log('from a we get: \n', a) | |
var b = gen.next('rutabega'); | |
console.log('from b we get: \n', b) | |
//Use cases: getting stuff from a database | |
// how we're used to seeing it done | |
asyncFunc('http://example.com', result => { | |
console.log(result); | |
}); | |
// with a Promise | |
asyncFunc('http://example.com') | |
.then(result => { | |
console.log(result); | |
}); | |
// with a Generator | |
Q.spawn(function* () { | |
let result = yield asyncFunc('http://www.youthebomb.com'); | |
console.log(result); | |
}); | |
/* | |
Resources: | |
"No promises: asynchronous JavaScript with only generators." | |
http://2ality.com/2015/03/no-promises.html | |
"The Hidden Power of ES6 Generators: Observable Async Flow Control." | |
https://medium.com/javascript-scene/the-hidden-power-of-es6-generators-observable-async-flow-control-cfa4c7f31435 | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment