From 58fae8c019981250ec9dab66f8ae0e91ad6e9573 Mon Sep 17 00:00:00 2001 From: "Rico Sta. Cruz" Date: Mon, 21 Sep 2015 13:14:36 +0800 Subject: [PATCH] Add co.js --- co.md | 54 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 co.md diff --git a/co.md b/co.md new file mode 100644 index 000000000..fc4733469 --- /dev/null +++ b/co.md @@ -0,0 +1,54 @@ +--- +title: co +--- + +[co]: https://github.com/tj/co +[thunkify]: https://github.com/visionmedia/node-thunkify +[unyield]: https://github.com/MatthewMueller/unyield + +[co] allows you to use generators to manage async flow. + +### Generator → promise + +A generator can `yield` a thunk or promise. Using `co()` will immediately invoke the block inside it. + +```js +co(function * () { + yield Promise.resolve(true) +}).then(...) +``` + +### Generator() → Promise() + +Use `co.wrap()`. Most of the time, you'll be using co.wrap. + +```js +var fn = co.wrap(function * (val) { + return yield Promise.resolve(val) +}) + +fn().then(...) +``` + +### Generator() → Node callback() + +Use [unyield]. (You can [thunkify] this later) + +```js +var get = unyield(function * () { +}) + +get(function (err, res) { ... }) +``` + +### Node callback() → Thunk() + +Use [thunkify]. You can yield this. + +```js +var readFile = thunkify(fs.readFile) + +co(function * () { + var data = yield readFile('index.txt', 'utf-8') +}) +```