所以我一直在阅读co库的用法,我在大多数博客文章中看到的一般设计模式是包装在 thunk 中具有回调的函数。然后使用 es6 生成器将这些 thunk 生成给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);
}
}
我可以理解,因为它带来了 Promise 的所有好处,比如更好的可读性和更好的错误处理。
但是,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 使代码看起来更加混乱。