Co v4
[email protected]
has been released, which now relies on promises. It is a stepping stone towards the aysnc/await proposal. The primary API change is how co()
is invoked. Before, co
returned a “thunk”, which you then called with a callback and optional arguments. Now, co()
return s a promise.
co(function* (){
var result = yield Promise.resolve(true);
return result;
}).then(function (value) {
console.log(value);
}, function(err) {
console.error(err.stack);
});
`</pre>
If you want to convert a `co`-generator-function into a regular function that returns a promise, you now use `co.wrap(fn*)`.
<pre>`var fn = co.wrap(function*(val) {
return yield Promise.resolve(val);
});
fn(true).then(function(val){
})
`</pre>
### Platform Compatibility
`co@4+` requires a `Promise` implementation. For version of node `< 0.11` and for many older browsers, you should/must include your own `Promise` polyfill.
Node v4+ is supported out of the box, you can use `co` without flags or polyfills.
### Installation
<pre>`$ npm install co
`</pre>
### Examples
<pre>`var co = require('co');
co(function*(){
// yield any promise
var result = yield Promise.resolve(true);
}).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(res);
// => [1,2,3]
}).catch(onerror);
// errors can be try/catched
co(function*() {
try{
yield Promise.reject(new Error('boom'));
} catch (err) {
console.error(err.message); // 'boom'
}
});
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);
}