在循环中执行POST请求

时间:2015-03-05 14:52:29

标签: javascript node.js post

我有数据(对象)数组:

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");
});

并且所有请求都发送了async。

1 个答案:

答案 0 :(得分:0)

您使用的是jQuery吗?

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

您可以执行类似

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

不是最简洁,但它会做到这一点,而且它会异步进行。

完整的dox:

for $.post

for $.each