brianc
brianc

Reputation: 1629

Node.js My Request is Not Blocking

I'm new to node.js, and I'm trying to call a service, parse its data and return it as part of a view. I can't seem to get the request to block until the response is complete. The console always logs 'wrong' before 'right' (returning the 1,2,3 array). What am I missing?

app.js

  var reading = require('./reading'); 

  app.get('/reading', function(req, res){
  res.render('reading/index.stache', 
    {
      locals : { ids : reading.list},
      partials : {
             list : '{{#ids}}{{.}}<br />{{/ids}}'
      }
  });
});

reading.js

var request,
    http = require('http'),
    host = 'google.com',
    path ='/';

var list = function(){

var connection = http.createClient(80, host),
    request = connection.request(path);

request.addListener('response', function(response){
    var data = '';
    response.addListener('data', function(chunk){ 
        data += chunk; 
    });
    response.addListener('end', function(){
        console.log('right')
        //var results = JSON.parse(data); 
        // i need results from json
        return [88234,883425,234588];
    });
});

request.end();
console.log('wrong');
return [1,2,3];
}

module.exports.list = list;

Upvotes: 2

Views: 1699

Answers (2)

Raynos
Raynos

Reputation: 169401

Of course you can't get the request to block until the response is back.

That's because there is communication latency between sending the request of and getting the response back. It would be stupid to wait and do nothing whilst that latency is happening.

Use callbacks and asynchronous control flow.

var list = function(callback){

var connection = http.createClient(80, host),
    request = connection.request(path);

request.addListener('response', function(response){
    var data = '';
    response.addListener('data', function(chunk){ 
        data += chunk; 
    });
    response.addListener('end', function(){
        console.log('right')
        // USE A CALLBACK >:(
        callback([88234,883425,234588]);
    });
});

request.end();
}

Upvotes: 3

user187676
user187676

Reputation:

If you wan't to run anything in sync have a look at the sync module. It's based on fibers.

Upvotes: 0

Related Questions