0

I have three ajax calls which can run concurrently. However I want the browser to wait until all ajax calls completed. One way is to set async as false for each of them but then I lose precious time since they can run concurrently. Is there a way to run them concurrently but make the browser hangs until all completed?

Nuri Tasdemir
  • 9,720
  • 3
  • 42
  • 67

4 Answers4

1

After success, call callback function:

$.ajax({
    success: function(){ checkAjax(); }
});

And in callback function count how much responses you have.

var totalEnded = 0, totalAjax = 3;
function checkAjax() {
   totalEnded++;

   if (totalEnded == totalAjax) {
       /* Do important stuff here, or call another function */
   }
}
Justinas
  • 41,402
  • 5
  • 66
  • 96
  • I want the browser hanged up on the ajax calls. Not just calling some javascript function when all is completed. – Nuri Tasdemir May 27 '14 at 08:41
  • @araqnoon Why you want to hang browser? If it takes longer to connect, i go to watch some YouTube. Better hide or disable some elements, so no interactiosn can be made while waiting for response. – Justinas May 27 '14 at 09:13
0

If you are using jQuery then have a look at $.when, you can provide a success callback which gets executed when all the requests are finished loading.

Mudassir Ali
  • 7,913
  • 4
  • 32
  • 60
0

To make work with asynchronous stuff easier, you can use the promises pattern. If you're on jQuery, you can use jQuery.when(). From the docs:

$.when( $.ajax( "/p1.php" ), $.ajax( "/p2.php" )).done(function( a1, a2 ) {
     //do this when both ajax calls are done
});
mfirdaus
  • 4,574
  • 1
  • 25
  • 26
0

You could do this using deferred objects, because ajax itself returns that object. Please refer to Pass in an array of Deferreds to $.when()

var deferreds = [
    $.post(),
    $.get(),
];
$.when.apply($, deferreds).done(function() {
    // All ajax requests was done
});
Community
  • 1
  • 1
Krzysztof Romanowski
  • 2,164
  • 2
  • 20
  • 29