co
's direct dependencies. Data on all dependencies, including transitive ones, is available via CSV download.Name | Version | Size | License | Type | Vulnerabilities |
---|
Co is a popular npm package that provides generator-based control flow for Node.js and browser applications. It enables developers to write non-blocking code in a neat and concise way compatibly with promises. Co essentially helps handle promises better, and it serves as a stepping stone towards using ES7 async/await.
The Co library is quite straightforward to use in your application. First, you need to install it in your project directory using npm as follows:
$ npm install co
Once installed, you can import it and use it in your JavaScript code. You can use co with generator function that yields Promise:
// Import co library
var co = require('co');
co(function* () {
// yield any promise
var result = yield Promise.resolve(true);
}).catch(function(err){
console.error(err.stack);
});
You can also resolve multiple promises in parallel:
var co = require('co');
co(function* () {
var a = Promise.resolve(1);
var b = Promise.resolve(2);
var c = Promise.resolve(3);
var res = yield [a, b, c]; // resolve a, b, c in parallel
console.log(res); // Logs [1, 2, 3]
}).catch(function(err){
console.error(err.stack);
});
If you want to convert a co-generator-function into a regular function that returns a promise, use co.wrap(fn*)
:
var co = require('co');
var fn = co.wrap(function* (val) {
return yield Promise.resolve(val);
});
fn(true).then(function (val) {
console.log(val); // Logs: true
});
The documentation for Co can be found in the README.md file available in the GitHub repository for the Co package. More in-depth examples, API reference, and other details can be found in this document. Note that it is important to handle all your errors in co to prevent any uncaught exceptions.