发现几乎不可能将循环中http请求的响应作为数组捕获。我可以在console.log中看到数组,但是当我传递数组作为http服务器的响应时,我得到一个空数组。我做错了什么,或者有更好的方法来做到这一点?在nodejs循环中发出http请求
代码:
router.route('/uprns').post(function(request, response){
response.setHeader('content-type', 'application/text');
console.log('first element from the array is '+request.body.UPRNS[0]);
console.log('Number of items in array is '+request.body.UPRNS.length);
if (request.body.UPRNS.length == 0) {
response.send('no UPRNS in request');
}
var output = [];
var obj = '';
for(var i = 0; i < request.body.UPRNS.length; i++) {
obj = request.body.UPRNS[i];
//Make HTTP calls to
var options = {
host: 'orbisdigital.azure-api.net',
path: '/nosecurity/addresses?uprn='+obj // full URL as path
};
callback = function(res) {
res.on('data', function (chunk) {
output.push(chunk.toString());
});
//the whole response has been recieved
res.on('end', function() {
console.log(output);
});
}
Https.request(options, callback).end();
}
response.send(output);
});
我知道有很多谈论在for循环阻塞进程的,但对付在循环HTTP调用没有明确推荐的方式。 谢谢。
输出数组中元素的顺序很重要?他是否应该遵守http请求的顺序? –
在我的情况下,订单并不重要,但想知道如何实现订单。 – noexpert