Deleter
Deleter

Reputation: 781

How to wait until multiple ajax requests are done?

I have some async ajax requests

$.ajax({
    url: 'first.php',
    async: true,
    success: function (data) {
        //do stuff
    }
});

$.ajax({
    url: 'second.php',
    async: true,
    success: function (data) {
        //do stuff
    }
});

...

$.ajax({
    url: 'nth.php',
    async: true,
    success: function (data) {
        //do stuff
    }
});

I want to run console.log() when every request is done.

I usually write this code:

$.ajax({
    url: 'first.php',
    async: true,
    success: function (data) {
        $.ajax({
            url: 'second.php',
            async: true,
            success: function (data) {
                //till the last ajax
            }
        });
    }
});

However someone suggest Promise.all([]).

If I had to run, lets say, 4 ajax requests, which method would be the best/quickest?

Upvotes: 3

Views: 757

Answers (2)

Zoli Szabó
Zoli Szabó

Reputation: 4534

The official jQuery documentation states that:

The jqXHR objects returned by $.ajax() as of jQuery 1.5 implement the Promise interface, giving them all the properties, methods, and behavior of a Promise (see Deferred object for more information).

jQuery.when():

Provides a way to execute callback functions based on zero or more Thenable objects, usually Deferred objects that represent asynchronous events.

So you can do something like:

jQuery.when(
    $.ajax({
        url: 'first.php',
        async: true,
        success: function (data) {
            //do stuff
        }
    }),

    $.ajax({
        url: 'second.php',
        async: true,
        success: function (data) {
            //do stuff
        }
    }),

    ...,

    $.ajax({
        url: 'nth.php',
        async: true,
        success: function (data) {
            //do stuff
        }
    })
).then(function() {console.log(...);});

Upvotes: 0

I wrestled a bear once.
I wrestled a bear once.

Reputation: 23379

Use Promise.all().

var promises = [];

promises.push(new Promise(done=>{
  $.ajax({
      url: 'first.php',
      async: true,
      success: done
  });
}));

promises.push(new Promise(done=>{
  $.ajax({
      url: 'second.php',
      async: true,
      success: done
  });
}));

promises.push(new Promise(done=>{
  $.ajax({
      url: 'nth.php',
      async: true,
      success: done
  });
}));

Promise.all(promises).then(()=>{
  console.log("All ajax completed.");
});

Upvotes: 3

Related Questions