gpt4 book ai didi

javascript - 将 co 库与 promises 一起使用而不是与 thunks 一起使用有什么好处?

转载 作者:数据小太阳 更新时间:2023-10-29 06:10:41 25 4
gpt4 key购买 nike

所以我一直在阅读有关 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 的所有好处,例如更好的可读性和更好的错误处理。

但是如果您已经有可用的 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 使代码看起来更加困惑。

最佳答案

没有真实案例,没有。除非你真的讨厌 promise 构造函数(在这种情况下,bluebird promisify 可以拯救)。

当您原生拥有 Promises 时,几乎所有使用单个值调用一次的回调的有效用例实际上都没有实际意义。

关于javascript - 将 co 库与 promises 一起使用而不是与 thunks 一起使用有什么好处?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34621909/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com