2016-07-08 46 views
1

我是node.js的新手,我正在开发一个代码库,通过将调用包装到生成器函数中来利用co库。一个简化的例子是这样的:co node.js库的用途是什么?

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和描述说:

“发电机基于控制流善良的NodeJS和浏览器,使用的承诺,让你写一个无阻塞码好的方式。“

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

yield saveData(this.query) 
+0

*这是不是代码无阻塞太node.js的背景下? *号迭代器和发生器是同步操作。 * co *库使用生成器语法来包装承诺,使异步代码看起来像是以同步方式编写的。 'yield saveData'会产生一个未解决的Promise – CodingIntrigue

+0

实际上'co(saveData(this.query));'生成器内部确实是垃圾。 – Bergi

+0

为什么垃圾?你能详细说明一下吗? –

回答

3

没有关于发电机功能的阻塞/非阻塞。它们只是表达可中断控制流的工具。

流程中断的方式只能由发生器的调用者来决定,在这种情况下,该库会在产生异步值时等待异步值。有很多方法对皮肤此猫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 
        } 
    }