co 进阶用法

1: co中数组的使用

map 传入的函数,也可以是个 generator。下面的代码解释如何处理

代码:array-co

/**
 * co array
 */

var co = require('co');  
var fs = require('mz/fs');

var paths = ['node_modules/co/', 'node_modules/mz/'];  
co(function* () {  
  var files = yield paths.map(function(path) {
    return fs.readdir(path);
  });
  var results = [];
  for (var i = 0; i < files.length; i++) {
    results[i] = yield files[i].map(function(file) {
      return fs.exists(file);
    });
  }
  console.log(results);
});

//better way
co(function* () {  
  var res = yield paths.map(function*(path) {
    var files = yield fs.readdir(path);
    var r = yield files.map(function(file) {
      return fs.exists(file);
    })
    return r;
  })
  console.log(res);
});

2: 使用thenify封装传统回调

var thenify = require('thenify');

var somethingAsync = thenify(function somethingAsync(a, b, c, callback) {  
  callback(null, a, b, c);
});

为了兼容以前的用法,你还可以这样用

var thenify = require('thenify').withCallback;

var somethingAsync = thenify(function somethingAsync(a, b, c, callback) {  
  callback(null, a, b, c);
});

// somethingAsync(a, b, c).then(onFulfilled).catch(onRejected);
// somethingAsync(a, b, c, function () {});