[英]execute POST requests in the loop
我有數據(對象)的數組:
var data = [
{"name":"Jon",
"age":22},
{"name":"Ioan",
"age":42},
{"name":"Jem",
"age":33},
... other more then 100 items
]
var http = require('http');
var options = {
hostname: 'localhost',
port: 80,
path: '/users',
method: 'POST',
headers: {
'Content-Type': 'application/json'
} };
//I create following function:
function sendData(data) {
var req = http.request(options, 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);
});
});
req.write(JSON.stringify(data));
req.end();
}
//end try send for each array item:
for (var i=0; i<data.length;i++) {
sendData(data[i]);
}
但是只發出了數組中的第一項。
如何將每個項目作為POST請求發送?
可能是最好的解決方案。
如果請求將作為異步執行,那將更好。
更新:
我找到了使用異步模塊的更好解決方案。 添加以下代碼:
var async = require("async");
var tasks = [];
for (i=0;i<result.length;i++) {
tasks.push(sendRequest(data[i]));
}
async.parallel(tasks, function(){
console.log("done");
});
並且所有請求wat發送異步。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.