簡體   English   中英

在循環中執行POST請求

[英]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發送異步。

你在使用jQuery嗎?

如果是這樣,您可以使用$.post方法和$.each方法。

你可以做點什么

$.each(data, function(index, val) {
    JSON.stringify(val);
    $.post(url, val)
     .done(function (data) {
         alert("got " + data + " back");
    });
});

不是最簡潔,但它會做到這一點,而且它會異步進行。

完整的dox:

對於$ .post

$ .each

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM