Created
June 23, 2015 19:02
-
-
Save yrezgui/2836363f412bb832e2bf to your computer and use it in GitHub Desktop.
Example of Generators using the "co" lib
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 co = require('co'); | |
| var i = 0 | |
| function getPromiseTime() { | |
| var t = ++i; | |
| return new Promise(function (resolve, reject) { | |
| setTimeout(function() { | |
| console.log(t + ' released'); | |
| resolve(t); | |
| }, t * 500); | |
| }); | |
| } | |
| function onerror(err) { | |
| // log any uncaught errors | |
| // co will not throw any errors you do not handle!!! | |
| // HANDLE ALL YOUR ERRORS!!! | |
| console.error(err.stack); | |
| } | |
| co(function *(){ | |
| // resolve multiple promises in parallel | |
| var a = getPromiseTime(); | |
| var b = getPromiseTime(); | |
| var c = getPromiseTime(); | |
| console.log('START'); | |
| var res = yield [a, b, c]; | |
| console.log(res); | |
| // => [1, 2, 3] | |
| }).catch(onerror); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment