我有一个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++;
});
}
这会创建一个无限循环。如何同步可变数量的请求?
谢谢!
答案 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);
});
}
}