我一直在阅读关于使用co库的文章,大多数博客文章中看到的通用设计模式是将具有回调函数的函数封装在thunk中。然后使用es6生成器将这些thunk yield到co
对象中。就像这样:
co(function *(){
var a = yield read(‘Readme.md’);
var b = yield read(‘package.json’);
console.log(a);
console.log(b);
});
function read(path) {
return function(done){
fs.readFile(path, ‘utf8', done);
}
}
我可以理解这一点,因为它带来了诸如更好的可读性和更好的错误处理等承诺的所有好处。
但是,如果您已经可以使用承诺,那么使用co
有什么意义呢?
co(function* () {
var res = yield [
Promise.resolve(1),
Promise.resolve(2),
Promise.resolve(3),
];
console.log(res); // => [1, 2, 3]
}).catch(onerror);
为什么不试试像这样的东西
Promise.all([
Promise.resolve(1),
Promise.resolve(2),
Promise.resolve(3),
]).then((res) => console.log(res)); // => [1, 2, 3]
}).catch(onerror);
对我而言,与 Promise 版本相比,co 使代码看起来更加混乱。