[英]Multiple ajax request in sequence using recursive function and execute callback function after all requests completed
我有用逗號分隔的名稱列表。 我想要的是我要為序列中的所有名稱調用服務器請求並將結果存儲在數組中。 我試過了,當我確實有很多名字存在於字符串中時,它就起作用了。
請參閱此處 -當我知道名字數量時,此方法有效
現在我想要的是使此代碼通用。 如果我在該字符串中添加一個名稱,它將自動處理而無需為ajax請求添加任何代碼。
請參閱此處 -這是我嘗試過的。 它沒有按預期工作。
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();
}
或者您實際上使用了諾言並做了
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([]));
}
( 更新了jsfiddle )
請注意,任務要求中沒有關於順序發出的Ajax請求的內容。 您還可以讓它們並行運行並等待所有它們完成 :
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);
})
}
( 更新了jsfiddle )
// global:
var pendingRequests = 0;
// after each ajax request:
pendingRequests++;
// inside the callback:
if (--pendingRequest == 0) {
// all requests have completed
}
我已將您的代碼進行了最小程度的修改以使其正常工作- Click here
。
請注意,由於無法以線性方式解決項目承諾,因此您最后的斷言將失敗。 因此,項目的順序將改變。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.