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 fill body1 with the result of a JSON response. However, the first is console.log('get_zillow : ' + body1);

never called - for some reason, the result is never closed, and the second console.log('get_zillow : ' + body1);

does not print anything since it is asynchronous and gets called before it is body1

populated.

In addition, I need to make similar requests to different external sites several times in a row, with each request depending on json from the previous result. Is there a way to do this without writing three messy internal callbacks and blocking somehow after the HTTP request?

+3


source to share


1 answer


Change

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

      

to



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

      

// new function defined

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

      

+3


source







All Articles