制作一个 http.request 返回 undefined

ale*_*ale 5 javascript node.js

我刚刚开始使用 Node.js。我有一个关于 http.request 的基本问题。我想编写一个带有几个函数的 JavaScript 模块,这些函数从几个服务器返回一些数据。

这是代码:

var mod = (function() {

    var my = {};
    var options = {
        hostname: 'example.com'
    };
    var foo = '';

    my.getBar = function() {
        var req = http.request(options, function(res) {
            res.setEncoding('utf8');
            res.on('data', function (chunk) {
                // example.com returns JSON
                // TODO need to be able to get foo from outside this module
                foo = JSON.parse(chunk).bar;
            });
        });
        req.end();
    }
    return my;
}());
Run Code Online (Sandbox Code Playgroud)

为了让bar我这样做:

console.log(mod.getBar());
Run Code Online (Sandbox Code Playgroud)

但我明白了undefined。我认为发生了一些异步事件.. get 请求发生了,当它发生时,我尝试打印尚未收到的结果?我想我需要让它同步还是什么?

非常感谢。

And*_*ren 5

如果您查看 getBar,它不会返回任何内容。这就是为什么你得到未定义。要获得结果,您必须向 getBar 发送回调:

getBar = function (callback){...
Run Code Online (Sandbox Code Playgroud)

并使用结果调用回调:

res.on('end, function(){
    callback(foo); 
});
Run Code Online (Sandbox Code Playgroud)

另外,我建议您将 foo 放在 getBar 的闭包中,以防您同时执行多个请求。同样,您应该只连接数据块并在最后解析它,以防响应对于一个块来说太长。

最后你的代码应该是这样的:

var mod = (function() {

    var my = {};
    var options = {
        hostname: 'example.com'
    };

    my.getBar = function(callback) {
        var foo = '';
        var req = http.request(options, function(res) {
            res.setEncoding('utf8');
            res.on('data', function (chunk) {
                foo += chunk;
            });
            res.on('end', function () {
                callback(null, JSON.parse(foo).bar); // The null is just to adhere to the de facto standard of supplying an error as first argument
            });
        });
        req.end();
    }
    return my;
}());
Run Code Online (Sandbox Code Playgroud)

像这样获取酒吧:

mod.getBar(function(err, data) {
    console.log(data);
});
Run Code Online (Sandbox Code Playgroud)