Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

co

tj78.8mMIT4.6.0TypeScript support: definitely-typed

generator async control flow goodness

async, flow, generator, coro, coroutine

readme

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

`co@4.0.0has been released, which now relies on promises. It is a stepping stone towards [ES7 async/await](https://github.com/lukehoban/ecmascript-asyncawait). The primary API change is howco()is invoked. Before,coreturned 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.11.x or greater, you must use the --harmony-generators flag or just --harmony to get access to generators.

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

io.js 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.

  • mz - wrap all of node's code libraries as promises.

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:

  • promises
  • thunks (functions)
  • array (parallel execution)
  • objects (parallel execution)
  • generators (delegation)
  • generator functions (delegation)

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

changelog

4.6.0 / 2015-07-09

  • support passing the rest of the arguments to co into the generator

    function *gen(...args) { }
    co(gen, ...args);

4.5.0 / 2015-03-17

  • support regular functions (that return promises)

4.4.0 / 2015-02-14

  • refactor isGeneratorFunction
  • expose generator function from co.wrap()
  • drop support for node < 0.12

4.3.0 / 2015-02-05

  • check for generator functions in a ES5-transpiler-friendly way

4.2.0 / 2015-01-20

  • support comparing generator functions with ES6 transpilers

4.1.0 / 2014-12-26

  • fix memory leak #180

4.0.2 / 2014-12-18

  • always return a global promise implementation

4.0.1 / 2014-11-30

  • friendlier ES6 module exports

4.0.0 / 2014-11-15

  • co now returns a promise and uses promises underneath
  • co.wrap() for wrapping generator functions

3.1.0 / 2014-06-30

  • remove setImmediate() shim for node 0.8. semi-backwards breaking. Users are expected to shim themselves. Also returns CommonJS browser support.
  • added key order preservation for objects. thanks @greim
  • replace q with bluebird in benchmarks and tests

3.0.6 / 2014-05-03

  • add setImmediate() fallback to process.nextTick
  • remove duplicate code in toThunk
  • update thunkify

3.0.5 / 2014-03-17

  • fix object/array test failure which tries to enumerate dates. Closes #98
  • fix final callback error propagation. Closes #92

3.0.4 / 2014-02-17

  • fix toThunk object check regression. Closes #89

3.0.3 / 2014-02-08

  • refactor: arrayToThunk @AutoSponge #88

3.0.2 / 2014-01-01

  • fixed: nil arguments replaced with error fn

3.0.1 / 2013-12-19

  • fixed: callback passed as an argument to generators

3.0.0 / 2013-12-19

  • fixed: callback passed as an argument to generators
  • change: co(function *(){}) now returns a reusable thunk
  • change: this must now be passed through the returned thunk, ex. co(function *(){}).call(this)
  • fix "generator already finished" errors

2.3.0 / 2013-11-12

  • add yield object support

2.2.0 / 2013-11-05

  • change: make the isGenerator() function more generic

2.1.0 / 2013-10-21

  • add passing of arguments into the generator. closes #33.

2.0.0 / 2013-10-14

  • remove callback in favour of thunk-only co(). Closes #30 [breaking change]
  • remove co.wrap() [breaking change]

1.5.2 / 2013-09-02

  • fix: preserve receiver with co.wrap()

1.5.1 / 2013-08-11

  • remove setImmediate() usage - ~110% perf increase. Closes #14

0.5.0 / 2013-08-10

  • add receiver propagation support
  • examples: update streams.js example to use http.get() and streams2 API

1.4.1 / 2013-07-01

  • fix gen.next(val) for latest v8. Closes #8

1.4.0 / 2013-06-21

  • add promise support to joins
  • add yield generatorFunction support
  • add yield generator support
  • add nested join support

1.3.0 / 2013-06-10

  • add passing of arguments

1.2.1 / 2013-06-08

  • fix join() of zero thunks

1.2.0 / 2013-06-08

  • add array yielding support. great suggestion by @domenic

1.1.0 / 2013-06-06

  • add promise support
  • change nextTick to setImmediate