Last active
August 29, 2015 14:10
-
-
Save gitawego/a90980ef92d3c878fc43 to your computer and use it in GitHub Desktop.
generator example
This file contains hidden or 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
| var commonJs = function(src,callback){ | |
| setTimeout(function(){ | |
| callback(null,{ | |
| src:src, | |
| style:"commonJs" | |
| }); | |
| },100); | |
| } | |
| var commonJsError = function(src,err,callback){ | |
| setTimeout(function(){ | |
| callback(new Error(err)); | |
| },100); | |
| } | |
| var promise = function(src){ | |
| return new Promise(function(resolve,reject){ | |
| setTimeout(function(){ | |
| resolve({ | |
| src:src, | |
| style:"promise" | |
| }); | |
| },100) | |
| }); | |
| } | |
| var readMultipleFiles = async(function* (){ | |
| var json1 = yield commonJs.bind(null,'test1.json'); | |
| var json2 = yield commonJs.bind(null,'test2.json'); | |
| var json3 = yield promise('test3.json'); | |
| var json4 = yield commonJsError.bind(null,'test4.json','error'); | |
| var json5 = yield commonJs.bind(null,'test5.json'); | |
| console.log(json1); | |
| console.log(json2); | |
| console.log(json3); | |
| }); | |
| //test function | |
| readMultipleFiles(); |
This file contains hidden or 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
| function async(makeGenerator){ | |
| return function (){ | |
| var generator = makeGenerator.apply(this, arguments); | |
| function handle(result){ // { done: [Boolean], value: [Object] } | |
| if (result.done) { | |
| return result.value; | |
| } | |
| if(result.value.then){ | |
| return result.value.then(function (res){ | |
| return handle(generator.next(res)); | |
| }, function (err){ | |
| return handle(generator.throw(err)); | |
| }); | |
| }else{ | |
| return result.value(function(err,res){ | |
| if(err){ | |
| handle(generator.throw(err)); | |
| }else{ | |
| handle(generator.next(res)); | |
| } | |
| }); | |
| } | |
| } | |
| return handle(generator.next()); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment