0

I am out after making multiple Ajax calls in a row and do something else when all of the requests are over.

The first round works fine because all of the requests return success 200. However, the second round fails to enter the done() method here due to the fact that some Ajax calls fail to respond ( they give 404 ). Let's say that the call ajaxCall(url5) fails by entering its own error function.

But still, I want to call a method inside the done() method so that I can make use of the responses that I get from the successful calls.

Any ideas why done() does not work when one of the calls fails OR how to make sure that I can be at the right spot when all of the calls are made regardless of their status is success or error?

function ajaxCall(endpoint){        
  return $.ajax({
    url: endpoint, 
    cache: false,
    error: function (xhr, ajaxOptions, thrownError) {          
      console.log("404");    
    },
    success: function(response) {
      result = $(response).find("#boxContent");       
      $(".boxContainer").append(result[0].innerHTML);     
    }
  });   
}

$.when(ajaxCall(url1),
       ajaxCall(url2),
       ajaxCall(url3),
       ajaxCall(url4),
       ajaxCall(url5)).then(function(){
  console.log("All requests issued.");
}, function() {      
  console.log("One of the sources is not available*****************"); 
  hasAnyFailed = true;
}).done(function( a1, a2, a3, a4, a5){      
  // When all calls return
  console.log("DONE*********);   
  doSomethingElse();
});  

PS : I found this SO solution, but not quite sure if we have an update solution like a built-in JS method. https://stackoverflow.com/a/7881733/2790804

shamaleyte
  • 1,882
  • 3
  • 21
  • 38
  • What version of jQuery are you using? Solution will be cleaner if using v 3+ – charlietfl Dec 01 '18 at 21:32
  • @charlietfl It is v1.7.1 , I am doing the implementation on HubSpot https://knowledge.hubspot.com/articles/kcs_article/cos-general/how-do-i-select-which-version-of-jquery-is-included-across-my-pages – shamaleyte Dec 01 '18 at 22:32
  • Can use `.always()` but won't have data passed to it. Or could write `ajaxCall()` to return a `jQuery.Deferred()` promise you create and have it resolve in both `success` and `error` – charlietfl Dec 01 '18 at 23:00
  • Can you give an example of such multiple calls ? – shamaleyte Dec 02 '18 at 16:35

0 Answers0