Wait until all jQuery Ajax requests are done?

后端 未结 21 1844
离开以前
离开以前 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:31

    If you want to know when all ajax requests are finished in your document, no matter how many of them exists, just use $.ajaxStop event this way:

    $(document).ajaxStop(function () {
      // 0 === $.active
    });
    

    In this case, neither you need to guess how many requests are happening in the application, that might finish in the future, nor dig into functions complex logic or find which functions are doing HTTP(S) requests.

    $.ajaxStop here can also be bound to any HTML node that you think might be modified by requst.


    Update:
    If you want to stick with ES syntax, then you can use Promise.all for known ajax methods:

    Promise.all([ajax1(), ajax2()]).then(() => {
      // all requests finished successfully
    }).catch(() => {
      // all requests finished but one or more failed
    })
    

    An interesting point here is that it works both with Promises and $.ajax requests.

    Here is the jsFiddle demonstration.


    Update 2:
    Yet more recent version using async/await syntax:

    try {
      const results = await Promise.all([ajax1(), ajax2()])
      // do other actions
    } catch(ex) { }
    
    0 讨论(0)
  • 2020-11-21 05:33

    I highly recommend using $.when() if you're starting from scratch.

    Even though this question has over million answers, I still didn't find anything useful for my case. Let's say you have to deal with an existing codebase, already making some ajax calls and don't want to introduce the complexity of promises and/or redo the whole thing.

    We can easily take advantage of jQuery .data, .on and .trigger functions which have been a part of jQuery since forever.

    Codepen

    The good stuff about my solution is:

    • it's obvious what the callback exactly depends on

    • the function triggerNowOrOnLoaded doesn't care if the data has been already loaded or we're still waiting for it

    • it's super easy to plug it into an existing code

    $(function() {
    
      // wait for posts to be loaded
      triggerNowOrOnLoaded("posts", function() {
        var $body = $("body");
        var posts = $body.data("posts");
    
        $body.append("<div>Posts: " + posts.length + "</div>");
      });
    
    
      // some ajax requests
      $.getJSON("https://jsonplaceholder.typicode.com/posts", function(data) {
        $("body").data("posts", data).trigger("posts");
      });
    
      // doesn't matter if the `triggerNowOrOnLoaded` is called after or before the actual requests 
      $.getJSON("https://jsonplaceholder.typicode.com/users", function(data) {
        $("body").data("users", data).trigger("users");
      });
    
    
      // wait for both types
      triggerNowOrOnLoaded(["posts", "users"], function() {
        var $body = $("body");
        var posts = $body.data("posts");
        var users = $body.data("users");
    
        $body.append("<div>Posts: " + posts.length + " and Users: " + users.length + "</div>");
      });
    
      // works even if everything has already loaded!
      setTimeout(function() {
    
        // triggers immediately since users have been already loaded
        triggerNowOrOnLoaded("users", function() {
          var $body = $("body");
          var users = $body.data("users");
    
          $body.append("<div>Delayed Users: " + users.length + "</div>");
        });
    
      }, 2000); // 2 seconds
    
    });
    
    // helper function
    function triggerNowOrOnLoaded(types, callback) {
      types = $.isArray(types) ? types : [types];
    
      var $body = $("body");
    
      var waitForTypes = [];
      $.each(types, function(i, type) {
    
        if (typeof $body.data(type) === 'undefined') {
          waitForTypes.push(type);
        }
      });
    
      var isDataReady = waitForTypes.length === 0;
      if (isDataReady) {
        callback();
        return;
      }
    
      // wait for the last type and run this function again for the rest of the types
      var waitFor = waitForTypes.pop();
      $body.on(waitFor, function() {
        // remove event handler - we only want the stuff triggered once
        $body.off(waitFor);
    
        triggerNowOrOnLoaded(waitForTypes, callback);
      });
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    
    <body>Hi!</body>

    0 讨论(0)
  • 2020-11-21 05:33

    Try this way. make a loop inside java script function to wait until the ajax call finished.

    function getLabelById(id)
    {
        var label = '';
        var done = false;
        $.ajax({
           cache: false,
           url: "YourMvcActionUrl",
           type: "GET",
           dataType: "json",
           async: false,
           error: function (result) {
             label='undefined';
             done = true;
            },
           success: function (result) {
                label = result.Message;
                done = true;
            }
         });
    
       //A loop to check done if ajax call is done.
       while (!done)
       {
          setTimeout(function(){ },500); // take a sleep.
       }
    
        return label;
    }
    
    0 讨论(0)
  • 2020-11-21 05:35

    Use the ajaxStop event.

    For example, let's say you have a loading ... message while fetching 100 ajax requests and you want to hide that message once loaded.

    From the jQuery doc:

    $("#loading").ajaxStop(function() {
      $(this).hide();
    });
    

    Do note that it will wait for all ajax requests being done on that page.

    0 讨论(0)
  • 2020-11-21 05:37

    I found a good answer by gnarf my self which is exactly what I was looking for :)

    jQuery ajaxQueue

    //This handles the queues    
    (function($) {
    
      var ajaxQueue = $({});
    
      $.ajaxQueue = function(ajaxOpts) {
    
        var oldComplete = ajaxOpts.complete;
    
        ajaxQueue.queue(function(next) {
    
          ajaxOpts.complete = function() {
            if (oldComplete) oldComplete.apply(this, arguments);
    
            next();
          };
    
          $.ajax(ajaxOpts);
        });
      };
    
    })(jQuery);
    

    Then you can add a ajax request to the queue like this:

    $.ajaxQueue({
            url: 'page.php',
            data: {id: 1},
            type: 'POST',
            success: function(data) {
                $('#status').html(data);
            }
        });
    
    0 讨论(0)
  • 2020-11-21 05:40

    As other answers mentioned you can use ajaxStop() to wait until all ajax request are completed.

    $(document).ajaxStop(function() {
         // This function will be triggered every time any ajax request is requested and completed
    });
    

    If you want do it for an specific ajax() request the best you can do is use complete() method inside the certain ajax request:

    $.ajax({
        type: "POST",
        url: "someUrl",
        success: function(data) {
            // This function will be triggered when ajax returns a 200 status code (success)
        },
        complete: function() {
            // This function will be triggered always, when ajax request is completed, even it fails/returns other status code
        },
        error: function() {
            // This will be triggered when ajax request fail.
        }
    });
    


    But, If you need to wait only for a few and certain ajax request to be done? Use the wonderful javascript promises to wait until the these ajax you want to wait are done. I made a shortly, easy and readable example to show you how does promises works with ajax.
    Please take a look to the next example. I used setTimeout to clarify the example.

    // Note:
    // resolve() is used to mark the promise as resolved
    // reject() is used to mark the promise as rejected
    
    $(document).ready(function() {
        $("button").on("click", function() {
    
            var ajax1 = new Promise((resolve, reject) => {
                $.ajax({
                    type: "GET",
                    url: "https://miro.medium.com/max/1200/0*UEtwA2ask7vQYW06.png",
                    xhrFields: { responseType: 'blob'},
                    success: function(data) {
                        setTimeout(function() {
                            $('#image1').attr("src", window.URL.createObjectURL(data));
                            resolve(" Promise ajax1 resolved");
                        }, 1000);
                    },
                    error: function() {
                        reject(" Promise ajax1 rejected");
                    },
                });
            });
    
            var ajax2 = new Promise((resolve, reject) => {
                $.ajax({
                    type: "GET",
                    url: "https://cdn1.iconfinder.com/data/icons/social-media-vol-1-1/24/_github-512.png",
                    xhrFields: { responseType: 'blob' },
                    success: function(data) {
                        setTimeout(function() {
                             $('#image2').attr("src", window.URL.createObjectURL(data));
                             resolve(" Promise ajax2 resolved");
                        }, 1500);
                    },
                    error: function() {
                        reject(" Promise ajax2 rejected");
                    },
                });
            });
    
            var ajax3 = new Promise((resolve, reject) => {
                $.ajax({
                    type: "GET",
                    url: "https://miro.medium.com/max/632/1*LUfpOf7teWvPdIPTBmYciA.png",
                    xhrFields: { responseType: 'blob' },
                    success: function(data) {
                        setTimeout(function() {
                             $('#image3').attr("src", window.URL.createObjectURL(data));
                             resolve(" Promise ajax3 resolved");
                        }, 2000);
                    },
                    error: function() {
                        reject(" Promise ajax3 rejected");
                    },
                });
            });
            
            Promise.all([ajax1, ajax2, ajax3]).then(values => {
                console.log("We waited until ajax ended: " + values);
                console.log("My few ajax ended, lets do some things!!")
            }, reason => {
                console.log("Promises failed: " + reason);
            });
            
            // Or if you want wait for them individually do it like this
            // ajax1.then(values => {
            //    console.log("Promise 1 resolved: " + values)
            // }, reason => {
            //     console.log("Promise 1 failed: " + reason)
            // });
        });
    
    });
    img {
      max-width: 200px;
      max-height: 100px;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <button>Make AJAX request</button>
    <div id="newContent">
        <img id="image1" src="">
        <img id="image2" src="">
        <img id="image3" src="">
    </div>

    0 讨论(0)
提交回复
热议问题