Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NodeJS return http.request

Hi now I know that NodeJS is asynchronous (which I am still trying to get my head around to be honest).

The problem that I am currently facing is I have attempting to do a http.request to receive some JSON data. This is fine but what I need is to return this data to a variable. I believe I need to do a callback function? (from what I have read up on the matter)

The Code that I currently have:

var http = require('http');
pCLatLng = '';

function postCodeCheck() {
    var pCode = { 
        host: 'geo.jamiethompson.co.uk',
        path: "/" + 'SW1A2AA' + ".json" 
    };

    http.request(pCode).on('response', function(response) {
        var data = '';
        response.on("data", function (chunk) {
            data += chunk;
        });
        response.on('end', function () {
            pCJSON = JSON.parse(data);
            pCLatLng = pCJSON;
        });
        }).end();
}

console.log(pCLatLng);

This is obviously outputting "undefined"; I have tried returning the response.on('end') when having return "hi" or anything inside it instead NodeJS outputs the information about the site. If anyone can help with this it would be much appreciated.

like image 854
Nick White Avatar asked Feb 17 '12 17:02

Nick White


1 Answers

console.log(pCLatLng); needs to be inside (or inside something called by) the response.on('end' callback. The value isn't available until that callback is fired.

Try something like:

function postCodeCheck(callback) {
    var pCode = { 
        host: 'geo.jamiethompson.co.uk',
        path: "/" + 'SW1A2AA' + ".json" 
    };

    http.request(pCode).on('response', function(response) {
        var data = '';
        response.on("data", function (chunk) {
            data += chunk;
        });
        response.on('end', function () {
            callback(JSON.parse(data));
        });
        }).end();
}

postCodeCheck(function (pCLatLng)
{
    console.log(pCLatLng);
});
like image 142
James McLaughlin Avatar answered Sep 18 '22 17:09

James McLaughlin