Skip to content

Instantly share code, notes, and snippets.

@jhyland87
Created September 30, 2016 16:21
Show Gist options
  • Save jhyland87/21deb5c4b563629dcb39151376d6340f to your computer and use it in GitHub Desktop.
Save jhyland87/21deb5c4b563629dcb39151376d6340f to your computer and use it in GitHub Desktop.
var co = require('co');
function getRandomArbitrary(min, max) {
return Math.floor(Math.random() * (max - min) + min);
}
co(function *(){
// yield any promise
//setTimeout(function(){
var result = yield Promise.resolve(true);
//}, getRandomArbitrary(1000,2000))
}).catch(onerror);
co(function *(){
// resolve multiple promises in parallel
var a = Promise.resolve(1);
var b = Promise.resolve(2);
var c = Promise.resolve(3);
var res = yield [a, b, c];
console.log('Result: ' + res);
// => [1, 2, 3]
}).catch(onerror);
// errors can be try/catched
co(function *(){
try {
yield Promise.reject(new Error('boom'));
} catch (err) {
console.error('Error: ' + err.message); // "boom"
}
}).catch(onerror);
function onerror(err) {
// log any uncaught errors
// co will not throw any errors you do not handle!!!
// HANDLE ALL YOUR ERRORS!!!
console.error('Error: ' + err.stack);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment