2015-09-21 05:14:36 +00:00
|
|
|
---
|
|
|
|
title: co
|
2015-11-24 05:02:17 +00:00
|
|
|
category: JavaScript libraries
|
2017-10-27 04:49:03 +00:00
|
|
|
updated: 2017-10-27
|
|
|
|
weight: -1
|
|
|
|
intro: |
|
|
|
|
[co](https://github.com/tj/co) allows you to use generators to manage async flow.
|
2015-09-21 05:14:36 +00:00
|
|
|
---
|
|
|
|
|
|
|
|
[co]: https://github.com/tj/co
|
|
|
|
[thunkify]: https://github.com/visionmedia/node-thunkify
|
|
|
|
[unyield]: https://github.com/MatthewMueller/unyield
|
2015-09-21 05:34:59 +00:00
|
|
|
[thenify]: https://www.npmjs.com/package/thenify
|
2015-09-21 05:32:35 +00:00
|
|
|
[mz]: https://www.npmjs.com/package/mz
|
2015-09-21 05:14:36 +00:00
|
|
|
|
2015-09-21 05:16:41 +00:00
|
|
|
### Running generators
|
2015-09-21 05:14:36 +00:00
|
|
|
|
|
|
|
```js
|
|
|
|
co(function * () {
|
|
|
|
yield Promise.resolve(true)
|
|
|
|
}).then(...)
|
|
|
|
```
|
|
|
|
|
2017-10-27 04:49:03 +00:00
|
|
|
A generator can `yield` a thunk or promise. Using `co()` will immediately invoke the block inside it.
|
2015-09-21 05:14:36 +00:00
|
|
|
|
2017-10-27 04:49:03 +00:00
|
|
|
### Generator → Promise
|
2015-09-21 05:14:36 +00:00
|
|
|
|
|
|
|
```js
|
|
|
|
var fn = co.wrap(function * (val) {
|
|
|
|
return yield Promise.resolve(val)
|
|
|
|
})
|
|
|
|
|
|
|
|
fn().then(...)
|
|
|
|
```
|
|
|
|
|
2017-10-27 04:49:03 +00:00
|
|
|
Use `co.wrap()`. Most of the time, you'll be using co.wrap.
|
2015-09-21 05:14:36 +00:00
|
|
|
|
2017-10-27 04:49:03 +00:00
|
|
|
### Generator → Node callback
|
2015-09-21 05:14:36 +00:00
|
|
|
|
|
|
|
```js
|
|
|
|
var get = unyield(function * () {
|
|
|
|
})
|
|
|
|
|
|
|
|
get(function (err, res) { ... })
|
|
|
|
```
|
|
|
|
|
2017-10-27 04:49:03 +00:00
|
|
|
Use [unyield]. (You can [thunkify] this later)
|
2015-09-21 05:14:36 +00:00
|
|
|
|
2017-10-27 04:49:03 +00:00
|
|
|
|
|
|
|
### Node callback → Thunk
|
2015-09-21 05:14:36 +00:00
|
|
|
|
|
|
|
```js
|
|
|
|
var readFile = thunkify(fs.readFile)
|
|
|
|
|
|
|
|
co(function * () {
|
|
|
|
var data = yield readFile('index.txt', 'utf-8')
|
|
|
|
})
|
|
|
|
```
|
2015-09-21 05:32:35 +00:00
|
|
|
|
2017-10-27 04:49:03 +00:00
|
|
|
Use [thunkify]. You can yield this. You can also use [thenify] too.
|
2015-09-21 05:32:35 +00:00
|
|
|
|
2017-10-27 04:49:03 +00:00
|
|
|
### Using Node.js API
|
2015-09-21 05:32:35 +00:00
|
|
|
|
|
|
|
```js
|
|
|
|
var readFile = require('mz/fs').readFile
|
|
|
|
|
|
|
|
var getLines = co.wrap(function * (filename) {
|
|
|
|
var data = yield readFile(filename, 'utf-8')
|
|
|
|
return data.split('\n')
|
|
|
|
})
|
|
|
|
|
|
|
|
getLines('file.txt').then((lines) => { ... })
|
|
|
|
```
|
2017-10-27 04:49:03 +00:00
|
|
|
|
|
|
|
Use [mz] for async Node.js API. You can also either [thunkify] or [thenify] them instead.
|