我有一个在循环内运行的ajax函数,它取决于数组中的项目数量。在完成ajax调用之后和循环之外,如何运行另一个函数?有可能吗?
这是功能
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);
}
答案 0 :(得分:2)
让所有调用成功后开始非常简单:
success: function(data){
downloads.push(data);
$('.loading').fadeOut("slow");
if(downloads.length===checked.length){//suppose checked is array like
alert("finish");
}
},
循环之外更难,因为它实际上不是一个循环,它需要一些修改。你基本上想要等待多个Promises(Promise.all):
Promise.all(checked.map(function(value){
return Promise(function(resolve){
$.ajax({... ,success:resolve});
});
})).then(function(downloads){
console.log("finished",downloads);
});