我有一个用逗号分隔的姓名列表。我想要的是我想调用服务器请求序列中的所有名称并将结果存储在数组中。我尝试过,当我确实有字符串中的名称时,它就可以工作。
参见Here - 当我知道名字的数量时,这才起作用
现在我想要的是让这段代码成为通用的。如果我在该字符串中添加一个名称,它应该自动处理,而无需添加任何 ajax 请求代码。
参见Here - 这是我尝试过的。它没有按预期工作。
shoppingList = shoppingList.split(",");
var result = [];
function fetchData(shoppingItem)
{
var s1 = $.ajax('/items/'+shoppingItem);
s1.then(function(res) {
result.push(new Item(res.label,res.price));
console.log("works fine");
});
if(shoppingList.length == 0)
{
completeCallback(result);
}
else
{
fetchData(shoppingList.splice(0,1)[0]);
}
}
fetchData(shoppingList.splice(0,1)[0]);
问题
我不知道如何检测所有 Promise 对象是否已解析,以便我可以调用回调函数。
最佳答案
要按顺序发出ajax请求,您必须将递归调用放在回调中:
function fetchList(shoppingList, completeCallback) {
var result = [];
function fetchData() {
if (shoppingList.length == 0) {
completeCallback(result);
} else {
$.ajax('/items/'+shoppingList.shift()).then(function(res) {
result.push(new Item(res.label,res.price));
console.log("works fine");
fetchData();
// ^^^^^^^^^^^
});
}
}
fetchData();
}
或者你实际上使用了 Promise 并执行了
function fetchList(shoppingList) {
return shoppingList.reduce(function(resultPromise, shoppingItem) {
return resultPromise.then(function(result) {
return $.ajax('/items/'+shoppingItem).then(function(res) {
result.push(new Item(res.label,res.price));
return result;
});
});
}, $.when([]));
}
( updated jsfiddle )
<小时/>请注意,任务中没有任何关于按顺序发出 ajax 请求的要求。您还可以让它们并行运行 wait for all of them to finish :
function fetchList(shoppingList) {
$.when.apply($, shoppingList.map(function(shoppingItem) {
return $.ajax('/items/'+shoppingItem).then(function(res) {
return new Item(res.label,res.price);
});
})).then(function() {
return Array.prototype.slice.call(arguments);
})
}
( updated jsfiddle )
关于javascript - 使用递归函数按顺序进行多个ajax请求,并在所有请求完成后执行回调函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27499833/