Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 508
maxko87 Avatar asked May 28 '26 16:05

maxko87


1 Answers

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
}
like image 152
Paresh Thummar Avatar answered May 30 '26 04:05

Paresh Thummar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!