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
这是什么?co 是一个面向 Node.js 的小型 JavaScript 库,提供基于生成器的流程控制:你可以编写异步、非阻塞的代码,读起来却像普通的顺序代码,底层使用 Promise。
它是我加到自己代码里的库,还是一个独立工具?是一个库:你从 npm 安装它,然后在 JavaScript 代码中 require 引入。它没有任何依赖,同一份源码还会构建出一个独立的浏览器版本(co-browser.js)。
怎么把它加进 Node 项目并开始使用?先用 npm install co 安装,然后 require 引入,再把你的异步步骤写在一个生成器函数(function*)里,传给 co(),例如 co(function* () { ... })。
需要特定的 Node 版本,或者要装 polyfill 才能用吗?co@4 及以上版本需要 Promise 实现,所以较旧的 Node 版本需要 polyfill;这个包针对 Node >= 0.12 和 io.js >= 1.0。
有什么坑——哪些地方容易让人栽跟头?你的异步代码必须写在生成器函数里,而且 v4 是一次破坏性变更:以前 co 返回的是一个 thunk,需要传入回调来调用,而 co@4 改为返回 Promise。
它也能在浏览器里运行,还是只能在 Node 里用?两者都可以:它同时面向 Node.js 和浏览器,仓库里还附带一个用 browserify 生成的独立浏览器版本(co-browser.js)。
我可以传什么给 co(),它会返回什么?可以传一个生成器、一个生成器函数,或者任何返回生成器的函数——co 会运行它,并返回一个代表整个流程的 Promise。
什么时候该用 co.wrap(),而不是直接调用 co()?co.wrap(fn) 会把生成器函数转换成一个返回 Promise 的普通函数,这样你就可以像普通函数一样把它保存起来,之后再带着参数调用。
它会引入依赖吗?不会——这个包没有任何运行时依赖;Promise 和生成器都是 JavaScript 平台本身提供的。
现在 JavaScript 已经原生支持 async/await 了,co 还有用吗?README 把 co@4 称为通向 async/await 提案的垫脚石,也就是说它的 API 预见了这门语言后来原生采纳的特性。如今的新代码用 async/await 就能实现同样的效果;co 主要还是对较老的 Node 代码库有意义。
Creator
tj
Size
0.4 MB
Stars
11.8K
Updated
CommitOct 17
Age
13y
Commits · 90 Days