在循环中的ajax完成后,Jquery调用另一个函数 [英] Jquery call another function after ajax in loop is done

查看:87
本文介绍了在循环中的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);
});

这篇关于在循环中的ajax完成后,Jquery调用另一个函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆