最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Making a http.request returns undefined - Stack Overflow

programmeradmin4浏览0评论

I'm just starting out on Node.js. I have a basic question about a http.request. I want to write a JavaScript module with a couple of functions that return some data from a couple of servers.

Here's the code:

var mod = (function() {

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

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

To get bar I do this:

console.log(mod.getBar());

but I get undefined. I think something asynchronous is happening.. get request happens, and while it is happening, I try and print the result which hasn't been received yet? I think I need to make it synchronous or something?

Many thanks.

I'm just starting out on Node.js. I have a basic question about a http.request. I want to write a JavaScript module with a couple of functions that return some data from a couple of servers.

Here's the code:

var mod = (function() {

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

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

To get bar I do this:

console.log(mod.getBar());

but I get undefined. I think something asynchronous is happening.. get request happens, and while it is happening, I try and print the result which hasn't been received yet? I think I need to make it synchronous or something?

Many thanks.

Share Improve this question asked May 7, 2013 at 9:16 aleale 11.8k27 gold badges98 silver badges150 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 5

If you look at getBar it doesn't return anything. That's why you get undefined. To get the result you'd have to send a callback to getBar:

getBar = function (callback){...

and call the callback with the result on end:

res.on('end, function(){
    callback(foo); 
});

Also I'd suggest you put foo inside getBar's closure in case you would do multiple requests at the same time. Likewise you should just concatenate the chunks on data and parse it on end, in case the response is too long for one chunk.

In the end your code should look like this:

var mod = (function() {

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

    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;
}());

Get the bar like this:

mod.getBar(function(err, data) {
    console.log(data);
});

Your function mod.getBar() doesn't have a return statement in it so it's only natural to return undefined.

On the other hand, if you want console.log() to write the content of foo variable from the res.on() event, you must do it directly in that function, as the mod.getBar() function only attaches the event listened to mod.

发布评论

评论列表(0)

  1. 暂无评论