在循环中的ajax完成后,Jquery调用另一个函数
问题描述:
我有一个在循环内运行的ajax函数,它取决于数组中的项目数量。在完成ajax调用之后和循环之外,如何运行另一个函数?有可能吗?
I have an ajax function that runs inside a loop and is dependent on the amount of items in the array. How do I run another function after the ajax call is done and outside the loop? Is it possible?
这是函数
function downloadAll(){
downloads = [];
$.each(checked, function(key, value) {
$.ajax({
method: "POST",
url: "<?php echo site_url($this->data['controller'].'/Download/'); ?>",
data:'id='+value,
beforeSend: function () {
$('.loading').show();
},
success: function(data){
downloads.push(data);
$('.loading').fadeOut("slow");
},
});
});
processZip(downloads);
}
答
让我们从开始在所有调用成功之后这很容易:
success: function(data){
downloads.push(data);
$('.loading').fadeOut("slow");
if(downloads.length===checked.length){//suppose checked is array like
alert("finish");
}
},
循环之外更难,因为它不是一个真正的循环,它需要一些修改。你基本上想要等待多个Promises(Promise.all):
Outside of the loop is more difficult as it isnt really a loop and it requires some modifications. You basically want to await multiple Promises (Promise.all):
Promise.all(checked.map(function(value){
return Promise(function(resolve){
$.ajax({... ,success:resolve});
});
})).then(function(downloads){
console.log("finished",downloads);
});