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?
'end'rather than'close'. And, you can't force blocking for an asynchronous task. But, there are flow control and promises/futures libraries that can help, such asasync(esp.async.waterfall).