[英]What are the benefits of using the co library with promises instead of with thunks?
So I've been reading about the usage of the co library, and the general design pattern I've seen in most blog posts is wrapping functions that have callbacks in thunks. 所以我一直在阅读co库的用法,我在大多数博客文章中看到的一般设计模式是包含回调函数的函数。 Then using an es6 generator to yield those thunks to the
co
object. 然后使用es6生成器将这些thunk产生到
co
对象。 Like this: 像这样:
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);
}
}
And that I can understand because it brings all the benefits of promises like better readability and better error handling. 而且我可以理解,因为它带来了承诺的所有好处,例如更好的可读性和更好的错误处理。
But what's the point of using co
if you already have promises available? 但是如果你已经有了承诺,那么使用
co
有什么意义呢?
co(function* () {
var res = yield [
Promise.resolve(1),
Promise.resolve(2),
Promise.resolve(3),
];
console.log(res); // => [1, 2, 3]
}).catch(onerror);
Why not something like 为什么不喜欢
Promise.all([
Promise.resolve(1),
Promise.resolve(2),
Promise.resolve(3),
]).then((res) => console.log(res)); // => [1, 2, 3]
}).catch(onerror);
To me, co makes the code look more confusing compared to the Promise version. 对我而言,与Promise版本相比,co使代码看起来更加混乱。
No real cases, no. 没有真实案例,没有。 Unless you really hate the promise constructor (in which case, bluebird
promisify
to the rescue). 除非你真的讨厌承诺构造函数(在这种情况下,bluebird
promisify
拯救)。
When you have Promises natively, nearly all valid usecases for callbacks that are called once with a single value are effectively moot. 当你本机拥有Promise时,几乎所有用于使用单个值调用一次的回调的有效用例实际上没有实际意义。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.