發現幾乎不可能將循環中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