使用带有promise而不是thunks的co-library有什么好处

What are the benefits of using the co library with promises instead of with thunks?

本文关键字:co-library 什么 thunks promise      更新时间:2023-09-26

所以我一直在阅读关于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);
  }
}

我能理解这一点,因为它带来了承诺的所有好处,比如更好的可读性和更好的错误处理。

但是,如果您已经有可用的承诺,那么使用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时,几乎所有使用单个值调用一次的回调的有效用例都是无效的。