OSDN Git Service

Regular updates
[twpd/master.git] / co.md
1 ---
2 title: co
3 category: JavaScript libraries
4 layout: 2017/sheet
5 updated: 2017-10-27
6 weight: -1
7 intro: |
8   [co](https://github.com/tj/co) allows you to use generators to manage async flow.
9 ---
10
11 [co]: https://github.com/tj/co
12 [thunkify]: https://github.com/visionmedia/node-thunkify
13 [unyield]: https://github.com/MatthewMueller/unyield
14 [thenify]: https://www.npmjs.com/package/thenify
15 [mz]: https://www.npmjs.com/package/mz
16
17 ### Running generators
18
19 ```js
20 co(function * () {
21   yield Promise.resolve(true)
22 }).then(...)
23 ```
24
25 A generator can `yield` a thunk or promise. Using `co()` will immediately invoke the block inside it.
26
27 ### Generator → Promise
28
29 ```js
30 var fn = co.wrap(function * (val) {
31   return yield Promise.resolve(val)
32 })
33
34 fn().then(...)
35 ```
36
37 Use `co.wrap()`. Most of the time, you'll be using co.wrap.
38
39 ### Generator → Node callback
40
41 ```js
42 var get = unyield(function * () {
43 })
44
45 get(function (err, res) { ... })
46 ```
47
48 Use [unyield]. (You can [thunkify] this later)
49
50
51 ### Node callback → Thunk
52
53 ```js
54 var readFile = thunkify(fs.readFile)
55
56 co(function * () {
57   var data = yield readFile('index.txt', 'utf-8')
58 })
59 ```
60
61 Use [thunkify]. You can yield this. You can also use [thenify] too.
62
63 ### Using Node.js API
64
65 ```js
66 var readFile = require('mz/fs').readFile
67
68 var getLines = co.wrap(function * (filename) {
69   var data = yield readFile(filename, 'utf-8')
70   return data.split('\n')
71 })
72
73 getLines('file.txt').then((lines) => { ... })
74 ```
75
76 Use [mz] for async Node.js API. You can also either [thunkify] or [thenify] them instead.