所以我有一个函数在for循环中执行ajax调用。当整个for循环完成时,我需要回调另一个函数。由于ajax调用是异步运行的,所以一旦for循环完成,我就无法调用下一个函数。 这是我的代码:
for(let i=0; i< industryArray.length; i++){
$.ajax({
url: myurl + "_api/web/lists/GetByTitle('library')/items",
method: "GET",
headers: { "Accept": "application/json; odata=verbose" },
success: function (data) {
RejectedSalesCount += data.d.results.length;
},
error: function (data) {
}
})
}
// Need to call myfunction() here
即使在执行ajax调用之前,也会调用myfunction()
。谢谢!
设置ajax异步状态为false然后它将起作用
这是设置ajax async false的示例
$.ajax({
url : "/submit/checkuser/",
type : "get",
async: false,
success : function(userStatus) {
if (userStatus == 'Disabled') { // check if user if disabled
} else if (userStatus == 'Deleted') { // check if user if deleted
} else {
};
},
error: function() {
connectionError();
}
});
现在它等待函数执行并移动到下一行
var pendingRequests=0;
for(let i=0; i< industryArray.length; i++){
if (condition) {
pendingRequests++;
$.ajax({
url: myurl + "_api/web/lists/GetByTitle('library')/items",
method: "GET",
headers: { "Accept": "application/json; odata=verbose" },
success: function (data) {
RejectedSalesCount += data.d.results.length;
pendingRequests--;
if(pendingRequests===0) {
otherFunction()
}
},
error: function (data) {
doSomethingWithError(data)
}
})
}
}