Product
Introducing Enhanced Alert Actions and Triage Functionality
Socket now supports four distinct alert actions instead of the previous two, and alert triaging allows users to override the actions taken for all individual alerts.
co
Advanced tools
Package description
The co npm package is a generator based flow-control utility for Node.js and the browser, making it easier to work with asynchronous JavaScript operations. It allows you to use generators to yield any function that returns a Promise. It can be used to simplify callback or promise-based code, especially in the context of async/await patterns.
Sequential Execution
This feature allows for sequential execution of asynchronous tasks. The code sample demonstrates how you can use co to run promises in sequence using a generator function, which yields a promise that resolves to true.
co(function* () {
var result = yield Promise.resolve(true);
return result;
}).then(function (value) {
console.log(value);
}, function (err) {
console.error(err.stack);
});
Error Handling
This feature demonstrates how co can be used for error handling in asynchronous operations. The code sample shows a generator function yielding a promise that gets rejected, and the error is caught and logged.
co(function* () {
try {
yield Promise.reject(new Error('Oops!'));
} catch (err) {
console.error(err.message);
}
});
Parallel Execution
This feature showcases how co can handle parallel execution of promises. The code sample illustrates a generator function yielding an array of promises, which co runs in parallel, and then logs the array of results.
co(function* () {
var res = yield [
Promise.resolve(1),
Promise.resolve(2),
];
return res;
}).then(function (value) {
console.log(value);
});
Bluebird is a fully featured promise library with focus on innovative features and performance. It provides utilities for working with promises including but not limited to parallel execution, which is similar to what co offers. However, Bluebird does not use generator functions.
Async is a utility module which provides straight-forward, powerful functions for working with asynchronous JavaScript. Although it does not use promises or generators in the same way as co, it offers similar functionalities in terms of controlling the flow of asynchronous operations.
Q is a promise library for JavaScript which provides a toolset for creating and composing asynchronous promises. It is similar to co in that it helps manage asynchronous operations, but it does not utilize generator functions for flow control.
Readme
Generator based flow-control goodness for nodejs (and soon the browser), using thunks or promises, letting you write non-blocking code in a nice-ish way.
Currently you must use the --harmony-generators
flag when
running node 0.11.x to get access to generators.
Co is careful to relay any errors that occur back to the generator, including those
within the thunk, or from the thunk's callback. "Uncaught" exceptions in the generator are
then either passed co()
's thunk or thrown.
Make sure to view the examples.
$ npm install co
fs
function wrappersexec
function wrappervar co = require('co');
co(function *(){
var a = yield get('http://google.com');
var b = yield get('http://yahoo.com');
var c = yield get('http://cloudup.com');
console.log(a.status);
console.log(b.status);
console.log(c.status);
})
co(function *(){
var a = get('http://google.com');
var b = get('http://yahoo.com');
var c = get('http://cloudup.com');
var res = yield [a, b, c];
console.log(res);
})
The "yieldable" objects currently supported are:
While co supports promises, you may return "thunks" from your functions,
which otherwise behaves just like the traditional node-style callback
with a signature of: (err, result)
.
For example take fs.readFile
, we all know the signature is:
fs.readFile(path, encoding, function(err, result){
});
To work with Co we need a function to return another function of the same signature:
fs.readFile(path, encoding)(function(err, result){
});
Which basically looks like this:
function read(path, encoding) {
return function(cb){
fs.readFile(path, encoding, cb);
}
}
This is what the co.wrap(fn)
utility function does for you.
When co
is invoked with a receiver it will propagate to most yieldables,
allowing you to alter this
.
var ctx = {};
function foo() {
assert(this == ctx);
}
co.call(ctx, function *(){
assert(this == ctx);
yield foo;
});
Pass a generator fn
which is immediately invoked. Any yield
expressions
within must return a "thunk", at which point co()
will defer execution.
var co = require('co');
var fs = require('fs');
function read(file) {
return function(fn){
fs.readFile(file, 'utf8', fn);
}
}
co(function *(){
var a = yield read('.gitignore');
var b = yield read('Makefile');
var c = yield read('package.json');
console.log(a);
console.log(b);
console.log(c);
});
You may also yield Generator
objects to support nesting:
var co = require('co');
var fs = require('fs');
function size(file) {
return function(fn){
fs.stat(file, function(err, stat){
if (err) return fn(err);
fn(null, stat.size);
});
}
}
function *foo(){
var a = yield size('.gitignore');
var b = yield size('Makefile');
var c = yield size('package.json');
return [a, b, c];
}
function *bar(){
var a = yield size('examples/parallel.js');
var b = yield size('examples/nested.js');
var c = yield size('examples/simple.js');
return [a, b, c];
}
co(function *(){
var a = yield foo();
var b = yield bar();
console.log(a);
console.log(b);
});
Or if the generator functions do not require arguments, simply yield
the function:
var request = require('superagent');
var get = co.wrap(request.get);
function *results() {
var a = yield get('http://google.com')
var b = yield get('http://yahoo.com')
var c = yield get('http://ign.com')
return [a.status, b.status, c.status]
}
co(function *(){
// 3 concurrent requests at a time
var a = yield results;
var b = yield results;
var c = yield results;
console.log(a, b, c);
// 9 concurrent requests
console.log(yield [results, results, results]);
});
Since co()
returns a thunk, you may pass a function to this thunk
to receive the return
values from the generator. Any error that occurs
is passed to this (sizes
) function.
var co = require('co');
var fs = require('fs');
var read = co.wrap(fs.readFile);
var sizes = co(function *(){
var a = yield read('.gitignore');
var b = yield read('Makefile');
var c = yield read('package.json');
return [a.length, b.length, c.length];
});
sizes(function(err, res){
console.log(res);
});
The co.wrap()
utility simply wraps a node-style function to return a thunk.
var co = require('co');
var fs = require('fs');
var read = co.wrap(fs.readFile);
co(function *(){
var a = yield read('.gitignore');
var b = yield read('Makefile', 'ascii');
var c = yield read('package.json', 'utf8');
console.log(a);
console.log(b);
console.log(c);
});
An example with redis:
var co = require('co')
var redis = require('redis')
var db = redis.createClient()
db.set = co.wrap(db.set)
db.get = co.wrap(db.get)
co(function *(){
yield db.set('foo', 'bar')
yield db.set('bar', 'baz')
var res = yield db.get('foo')
console.log('foo -> %s', res);
var res = yield db.get('bar')
console.log('bar -> %s', res);
})
The co.join()
utility function allows you to pass multiple thunks, or an array
of thunks and "join" them all into a single thunk which executes them all concurrently,
instead of in sequence. Note that the resulting array ordering is retained.
var co = require('co');
var join = co.join;
var fs = require('fs');
function size(file) {
return function(fn){
fs.stat(file, function(err, stat){
if (err) return fn(err);
fn(null, stat.size);
});
}
}
co(function *(){
var a = size('.gitignore');
var b = size('index.js');
var c = size('Makefile');
var res = yield join(a, b, c);
console.log(res);
// => [ 13, 1687, 129 ]
});
As an alias of join(array)
you may simply yield
an array:
co(function *(){
var a = size('.gitignore');
var b = size('index.js');
var c = size('Makefile');
var res = yield [a, b, c];
console.log(res);
// => [ 13, 1687, 129 ]
});
Nested joins may also be expressed as simple nested arrays:
var a = [
get('http://google.com'),
get('http://yahoo.com'),
get('http://ign.com')
];
var b = [
get('http://google.com'),
get('http://yahoo.com'),
get('http://ign.com')
];
console.log(yield [a, b]);
On my machine 30,000 sequential stat()s takes an avg of 570ms,
while the same number of sequential stat()s with co()
takes
610ms, aka the overhead introduced by generators is extremely negligable.
MIT
FAQs
generator async control flow goodness
The npm package co receives a total of 17,601,768 weekly downloads. As such, co popularity was classified as popular.
We found that co demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 3 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Product
Socket now supports four distinct alert actions instead of the previous two, and alert triaging allows users to override the actions taken for all individual alerts.
Security News
Polyfill.io has been serving malware for months via its CDN, after the project's open source maintainer sold the service to a company based in China.
Security News
OpenSSF is warning open source maintainers to stay vigilant against reputation farming on GitHub, where users artificially inflate their status by manipulating interactions on closed issues and PRs.