[英]Jquery call another function after ajax in loop is done
I have an ajax function that runs inside a loop and is dependent on the amount of items in the array. 我有一个循环内运行的ajax函数,它取决于数组中项目的数量。 How do I run another function after the ajax call is done and outside the loop?
在ajax调用完成之后,如何在循环之外运行另一个函数? Is it possible?
可能吗?
This is the function 这是功能
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);
}
Lets start with after all calls succeded which is quite easy: 让我们从所有调用成功之后开始,这很容易:
success: function(data){
downloads.push(data);
$('.loading').fadeOut("slow");
if(downloads.length===checked.length){//suppose checked is array like
alert("finish");
}
},
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):
您基本上想等待多个Promises(Promise.all):
Promise.all(checked.map(function(value){
return Promise(function(resolve){
$.ajax({... ,success:resolve});
});
})).then(function(downloads){
console.log("finished",downloads);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.