如何同步执行可变数量的POST请求?

时间:2017-03-09 02:36:57

标签: javascript node.js express

我有一个items数组,需要按顺序POST编辑。

var items = ["data 1", "data 2", etc];
while (i < numOfItems) {    
    var formData = {
        ID : ID,
        UID : UID,
        item : items[i];
    }
    request.post({url:'http://example.com/a', formData: formData}, function(err, httpResponse, body){ 
        if (err) {
            return console.error('Post failed:', err);
        }
        console.log('Post successful!  Server responded with:', body);
        i++;
    });
}

这会创建一个无限循环。如何同步可变数量的请求?

谢谢!

1 个答案:

答案 0 :(得分:1)

您发布的代码的最简单解决方案是递归

var items = ["data 1", "data 2", etc];
function doRequest(i) {
    if (i< numOfItems) {
        var formData = {
            ID : ID,
            UID : UID,
            item : items[i];
        }
        request.post({url:'http://example.com/a', formData: formData}, function(err, httpResponse, body){ 
            if (err) {
                // this will stop the "loop" altogether
                return console.error('Post failed:', err);
            }
            console.log('Post successful!  Server responded with:', body);
            doRequest(++i);
        });
    }
}