Nick White
Nick White

Reputation: 1612

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.

Upvotes: 6

Views: 12513

Answers (3)

Dan D.
Dan D.

Reputation: 74645

You want something like this:

var http = require('http');

function postCodeCheck(cb) {
    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 () {
            var pCJSON = JSON.parse(data);
            cb(pCJSON);
        });
        }).end();
}

postCodeCheck(function(pCLatLng) { console.log(pCLatLng); });

Look carefully for the differences before using.

Upvotes: 1

tmcw
tmcw

Reputation: 11882

You'll need your postCodeCheck() function to take a callback as well, just like http.request. In the world of async, calling callbacks with results takes a similar role to returning results.

Upvotes: 0

James M
James M

Reputation: 16718

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

Upvotes: 7

Related Questions