2012-02-26 86 views
2

我是新来的node.js,我试图调用一个服务,解析它的数据并将它作为视图的一部分返回。我似乎无法得到阻止请求,直到响应完成。控制台总是在'正确'之前记录'错误'(返回1,2,3数组)。我错过了什么?Node.js我的请求不阻止

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; 
+0

不是你的问题的答案,但我只想指出,你需要'请求'模块,但是然后使用Node的核心'createClient'来代替。 – loganfsmyth 2012-02-26 15:00:20

+0

对不起,这是从其他尝试遗留下来的.... – bluevoodoo1 2012-02-26 15:31:03

回答

3

当然,在响应回来之前,您无法获得阻止请求。

这是因为发送请求和获取响应之间存在通信延迟。在这种潜伏期正在发生的时候,等待并且什么都不做是愚蠢的。

使用回调和异步控制流。

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(); 
} 
+2

您通过使用'+ ='隐式地将缓冲区转换为字符串。如果你要这样追加,那么你需要执行'response.setEncoding('utf8'),否则你可能会在响应中破坏多字节字符。 – loganfsmyth 2012-02-26 14:58:28

+1

那么,这不完全是什么被称为“阻塞”,但“回调”... – 2012-02-26 15:38:11

+0

我如何使用这在我的app.js的上下文? res.render(...)是回调函数吗? – bluevoodoo1 2012-02-26 15:48:41

0

如果您wan't运行同步什么都看看sync module。它基于纤维。