co README

The project's README from github.com/tj/co. As one markdown file: README.md.

co

Gitter NPM version Build status Test coverage Downloads

Generator based control flow goodness for nodejs and the browser, using promises, letting you write non-blocking code in a nice-ish way.

Co v4

[email protected] has been released, which now relies on promises. It is a stepping stone towards the async/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() returns a promise.

co(function* () {
  var result = yield Promise.resolve(true);
  return result;
}).then(function (value) {
  console.log(value);
}, function (err) {
  console.error(err.stack);
});

If you want to convert a co-generator-function into a regular function that returns a promise, you now use co.wrap(fn*).

var fn = co.wrap(function* (val) {
  return yield Promise.resolve(val);
});

fn(true).then(function (val) {

});

Platform Compatibility

co@4+ requires a Promise implementation. For versions of node < 0.11 and for many older browsers, you should/must include your own Promise polyfill.

When using node 0.10.x and lower or browsers without generator support, you must use gnode and/or regenerator.

When using node 0.11.x, you must use the --harmony-generators flag or just --harmony to get access to generators.

Node v4+ is supported out of the box, you can use co without flags or polyfills.

Installation

$ npm install co

Associated libraries

Any library that returns promises work well with co.

View the wiki for more libraries.

Examples

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"
 }
}).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(err.stack);
}

Yieldables

The yieldable objects currently supported are:

Nested yieldable objects are supported, meaning you can nest promises within objects within arrays, and so on!

Promises

Read more on promises!

Thunks

Thunks are functions that only have a single argument, a callback. Thunk support only remains for backwards compatibility and may be removed in future versions of co.

Arrays

yielding an array will resolve all the yieldables in parallel.

co(function* () {
  var res = yield [
    Promise.resolve(1),
    Promise.resolve(2),
    Promise.resolve(3),
  ];
  console.log(res); // => [1, 2, 3]
}).catch(onerror);

Objects

Just like arrays, objects resolve all yieldables in parallel.

co(function* () {
  var res = yield {
    1: Promise.resolve(1),
    2: Promise.resolve(2),
  };
  console.log(res); // => { 1: 1, 2: 2 }
}).catch(onerror);

Generators and Generator Functions

Any generator or generator function you can pass into co can be yielded as well. This should generally be avoided as we should be moving towards spec-compliant Promises instead.

API

co(fn*).then( val => )

Returns a promise that resolves a generator, generator function, or any function that returns a generator.

co(function* () {
  return yield Promise.resolve(true);
}).then(function (val) {
  console.log(val);
}, function (err) {
  console.error(err.stack);
});

var fn = co.wrap(fn*)

Convert a generator into a regular function that returns a Promise.

var fn = co.wrap(function* (val) {
  return yield Promise.resolve(val);
});

fn(true).then(function (val) {

});

License

MIT

co (tj/co)

Searching Database…

11.8K ·GitHub
What is this?co is a small JavaScript library for Node.js that gives you generator-based control flow: you write async, non-blocking code that reads like normal sequential code, with promises underneath.
Is it a library I add to my code, or a standalone tool?A library: you install it from npm and require it in your JavaScript code. It has zero dependencies, and a standalone browser bundle (co-browser.js) is built from the same source.
How do I add it to a Node project and start using it?Install with npm install co, require it, then write your async steps inside a generator function (function*) and pass it to co(), e.g. co(function* () { ... }).
Do I need a specific Node version or a polyfill for it to work?co@4+ requires a Promise implementation, so older Node versions need a polyfill; the package targets Node >= 0.12 and io.js >= 1.0.
What is the catch - anything that might trip me up?Your async code has to live in generator functions, and v4 was a breaking change: co used to return a thunk that you called with a callback, while co@4 returns a promise instead.
Does it run in the browser too, or only in Node?Both: it is built for Node.js and the browser, and the repo ships a standalone browser bundle (co-browser.js) produced with browserify.
What can I pass to co(), and what do I get back?A generator, a generator function, or any function that returns a generator - co runs it and hands you back a single promise for the whole flow.
When would I use co.wrap() instead of calling co() directly?co.wrap(fn) converts a generator function into a regular function that returns a promise, so you can store it and call it later with arguments like any normal function.
Does it pull in any dependencies?No - the package has zero runtime dependencies; promises and generators come from the JavaScript platform itself.
Is co still relevant now that JavaScript has native async/await?The README calls co@4 a stepping stone towards the async/await proposal, meaning its API anticipated what the language later adopted natively. New code today covers the same ground with async/await; co mainly matters for older Node codebases.
Creator
tj
Size
0.4 MB
Stars
11.8K
Updated
CommitOct 17
Age
13y
Commits · 90 Days