0

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?

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);
}
1
  • 1
    You can try by keeping a counter and increment it in success and check if(counter==checkedItemlength) then call processZip(downloads) Commented Jul 1, 2017 at 13:30

1 Answer 1

2

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):

Promise.all(checked.map(function(value){
 return Promise(function(resolve){
  $.ajax({... ,success:resolve});
 });
})).then(function(downloads){
 console.log("finished",downloads);
});
Sign up to request clarification or add additional context in comments.

1 Comment

Oh! I think the check the downloads length matches the checked length is great! Thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.