gpt4 book ai didi

node.js - co node.js 库的用途是什么?

转载 作者:太空宇宙 更新时间:2023-11-03 23:04:41 25 4
gpt4 key购买 nike

我是 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)

最佳答案

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

流程如何中断仅由生成器的调用者决定,在本例中是 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
    }
    }

关于node.js - co node.js 库的用途是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38266425/

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