70 likes | 215 Views
Generators, Real- ish Example . Presented By: Angello Pozo At: Downtown LA Node Meetup. Outline. Some* Details What Are Generators Thunks Examples Question /resources. Some* Details. Creating a Generator Iterating generator Using Generators Yield * Returns optional For.
E N D
Generators,Real-ish Example Presented By: AngelloPozo At: Downtown LA Node Meetup
Outline • Some* Details • What Are Generators • Thunks • Examples • Question/resources
Some* Details • Creating a Generator • Iterating generator • Using Generators • Yield * • Returns optional • For • Gen = Function *() { }; • Gen.next() • node 0.11: --harmony flag • Allow generator method to control iteration • Be careful with return • for (varitGenof generator()) { console.log( itGen); }
What Are Generators • An Iterable Function created at Yield • Think how arrays are really objects var first = function *(){ yield "First Place”; return 1; } varmyGen = function *() { var one = yeild*first(); //returns 1 var two = yeild *second(); //returns 2 var three = yeild*third(); //returns 3 } variterable = myGen(); var out1 = it.next() //returns { value: 'First Place', done: false } var out2 = it.next(); //returns { value: ’Second Place', done: false } var out3 = it.next(); //returns { value: 'Third Place', done: false } var out4 = it.next(); //returns { value: undefined, done: true } myGen = { 0 : first(), 1 : second(), 2 : third() }
Thunks A thunkis a method that wraps around the original method, while controlling the callback function orig(data, cb){ //do operations return cb(null, data); } function thunk_orig(data){ returns function(cb){ orig(data, cb); } }
Examples • Examples can be found at: • https://github.com/sogoiii/generator_uber_examples • We are going to use all 3 uber endpoints • Price • Product • Time • We are going to make one giant object containing each endpoint.
Questions? • Resources: • http://davidwalsh.name/es6-generators • https://github.com/petkaantonov/bluebird/blob/master/API.md#generators • https://github.com/visionmedia/co#thunks-vs-promises • http://strongloop.com/strongblog/node-js-callback-hell-promises-generators/ • http://tobyho.com/2013/06/16/what-are-generators/