【问题标题】:What is the purpose of the co node.js library?co node.js 库的目的是什么?
【发布时间】:2016-11-11 00:12:55
【问题描述】:

我是 node.js 的新手,正在开发一个代码库,它通过包装对生成器函数的调用来利用 co 库。一个简化的示例如下所示:

module.exports.gatherData = function*()
{
  // let img = //get the 1 pixel image from somewhere
  // this.type = "image/gif";
  // this.body = img;

  co(saveData(this.query));
  return;

};

function *saveData(query)
{   
  if(query.sid && query.url)
  {
      // save the data
  }
}

于是我去了github上的co主页,描述说:

“基于生成器的 nodejs 和浏览器控制流的优点,使用 Promise,让您以一种不错的方式编写非阻塞代码。”

在 node.js 的上下文中,这段代码难道不是非阻塞的吗?

yield saveData(this.query)

【问题讨论】:

  • 这段代码在 node.js 的上下文中难道不是非阻塞的吗? 不,迭代器和生成器是同步操作。 co 库使用生成器语法来包装承诺,以使异步代码看起来像是以同步方式编写的。 yield saveData 只会产生一个未解决的 Promise
  • 其实co(saveData(this.query));在生成器里面确实是垃圾。
  • 为什么是垃圾?你能详细说明一下吗?

标签: node.js ecmascript-6 generator


【解决方案1】:

生成器函数没有阻塞/非阻塞。它们只是表达可中断控制流的工具。

流程如何中断仅由生成器的调用者决定,在这种情况下,co 库在产生异步值时会等待它们。用co给这只猫剥皮的方法有很多:

  • module.exports.gatherData = co.coroutine(function*() {
      …
      yield saveData(this.query));
    });
    var saveData = co.coroutine(function* (query) {   
      if(query.sid && query.url) {
          // save the data
      }
    });
    
  • module.exports.gatherData = co.coroutine(function*() {
      …
      yield co(saveData(this.query));
    });
    function *saveData(query) {   
      if(query.sid && query.url) {
          // save the data
      }
    }
    
  • module.exports.gatherData = co.coroutine(function*() {
      …
      yield* saveData(this.query));
    });
    function *saveData(query) {   
      if(query.sid && query.url) {
          // save the data
      }
    }
    

【讨论】:

    猜你喜欢
    • 2014-10-04
    • 2016-04-09
    • 2013-10-14
    • 2011-05-27
    • 2023-03-04
    • 1970-01-01
    • 2012-04-08
    • 1970-01-01
    • 2016-11-13
    相关资源
    最近更新 更多