skip to Main Content

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?

2

Answers


  1. 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.");
    });
    Login or Signup to reply.
  2. 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(...);});
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search