Wait until all jQuery Ajax requests are done?

后端 未结 21 1853
离开以前
离开以前 2020-11-21 04:39

How do I make a function wait until all jQuery Ajax requests are done inside another function?

In short, I need to wait for all Ajax requests to be done before I exe

21条回答
  •  别那么骄傲
    2020-11-21 05:16

    NOTE: The above answers use functionality that didn't exist at the time that this answer was written. I recommend using jQuery.when() instead of these approaches, but I'm leaving the answer for historical purposes.

    -

    You could probably get by with a simple counting semaphore, although how you implement it would be dependent on your code. A simple example would be something like...

    var semaphore  = 0,     // counting semaphore for ajax requests
        all_queued = false; // bool indicator to account for instances where the first request might finish before the second even starts
    
    semaphore++;
    $.get('ajax/test1.html', function(data) {
        semaphore--;
        if (all_queued && semaphore === 0) {
            // process your custom stuff here
        }
    });
    
    semaphore++;
    $.get('ajax/test2.html', function(data) {
        semaphore--;
        if (all_queued && semaphore === 0) {
            // process your custom stuff here
        }
    });
    
    semaphore++;
    $.get('ajax/test3.html', function(data) {
        semaphore--;
        if (all_queued && semaphore === 0) {
            // process your custom stuff here
        }
    });
    
    semaphore++;
    $.get('ajax/test4.html', function(data) {
        semaphore--;
        if (all_queued && semaphore === 0) {
            // process your custom stuff here
        }
    });
    
    // now that all ajax requests are queued up, switch the bool to indicate it
    all_queued = true;
    

    If you wanted this to operate like {async: false} but you didn't want to lock the browser, you could accomplish the same thing with a jQuery queue.

    var $queue = $("
    "); $queue.queue(function(){ $.get('ajax/test1.html', function(data) { $queue.dequeue(); }); }).queue(function(){ $.get('ajax/test2.html', function(data) { $queue.dequeue(); }); }).queue(function(){ $.get('ajax/test3.html', function(data) { $queue.dequeue(); }); }).queue(function(){ $.get('ajax/test4.html', function(data) { $queue.dequeue(); }); });

提交回复
热议问题