co node.js库的目的是什么?

我是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主页,描述如下:

“基于生成器的nod​​ejs和浏览器的控制stream程的优点,使用promise,让你以一种很好的方式编写非阻塞代码。”

在node.js的情况下,这个代码是不是也是非阻塞的?

 yield saveData(this.query) 

发电机function没有阻塞/不阻塞。 它们只是expression可中断控制stream的工具。

stream程是如何中断的,只能由生成器的调用者决定,在这种情况下, co库会在产生asynchronous值时等待asynchronous值。 有很多方法可以用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 } }