maxko87
maxko87

Reputation: 2940

How to block after http request with Node.js

I have the following code:

var options1 = {
  host: 'maps.googleapis.com',
  port: 80,
  path: "/maps/api/geocode/json?latlng=" + lat + "," + lng + "&sensor=false",
  method: 'GET',
  headers: {
      'Content-Type': 'application/json'
  }
};

var body1 = "";

var req = http.request(options1, function(res) {
  console.log('STATUS: ' + res.statusCode);
  console.log('HEADERS: ' + JSON.stringify(res.headers));
  res.setEncoding('utf8');
  res.on('data', function (chunk) {
    //console.log('BODY: ' + chunk);
    body1 += chunk;
  });
  res.on('close', function () {
    console.log('get_zillow : ' + body1);
  });
});

req.on('error', function(e) {
  console.log('problem with request: ' + e.message);
});

req.end();

console.log('get_zillow : ' + body1);

I need to populate body1 with the result of the JSON response. However, the first console.log('get_zillow : ' + body1); never gets called -- for some reason the result never closes -- and the second console.log('get_zillow : ' + body1); prints nothing, since it is asynchronous and gets called before body1 gets populated.

Additionally, I need to make similar requests to different external sites several times in succession, with each request dependent on the json from the previous result. Is there any way to do this without writing three messy inner callbacks, and somehow block after an http request?

Upvotes: 3

Views: 6401

Answers (1)

Paresh Thummar
Paresh Thummar

Reputation: 928

Change

res.on('close', function () {
    console.log('get_zillow : ' + body1);
  });

to

res.on('end', function () {
     callback_function(body1);
});

//defined new function

function callback_function(finaldata)
{
 // handle your final data
}

Upvotes: 3

Related Questions