3

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?

4
  • 3
    Whenever I hear "block" and "javascript" in one sentence, I know the answer is going to be negative. Commented Jan 19, 2013 at 9:32
  • You can't avoid callbacks (AFAIK), but you can avoid nesting by supplying the callback by name (instead of inline in the call) Commented Jan 19, 2013 at 9:34
  • 2
    Try '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 as async (esp. async.waterfall). Commented Jan 19, 2013 at 9:50
  • 1
    You may be interested in this screencast, which covers this kind of thing: nodecasts.net/episodes/5-thinking-asynchronously (full disclosure, I am the author) Commented Jan 19, 2013 at 10:02

1 Answer 1

3

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
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.