简体   繁体   中英

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?

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."); });

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(...);});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM