Wait until all jQuery Ajax requests are done?

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

    I'm using size check when all ajax load completed

    function get_ajax(link, data, callback) {
        $.ajax({
            url: link,
            type: "GET",
            data: data,
            dataType: "json",
            success: function (data, status, jqXHR) {
                callback(jqXHR.status, data)
            },
            error: function (jqXHR, status, err) {
                callback(jqXHR.status, jqXHR);
            },
            complete: function (jqXHR, status) {
            }
        })
    }
    
    function run_list_ajax(callback){
        var size=0;
        var max= 10;
        for (let index = 0; index < max; index++) {
            var link = 'http://api.jquery.com/ajaxStop/';
            var data={i:index}
            get_ajax(link,data,function(status, data){
                console.log(index)
                if(size>max-2){
                    callback('done')
                }
                size++
                
            })
        }
    }
    
    run_list_ajax(function(info){
        console.log(info)
    })
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>

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

    If you need something simple; once and done callback

            //multiple ajax calls above
            var callback = function () {
                if ($.active !== 0) {
                    setTimeout(callback, '500');
                    return;
                }
                //whatever you need to do here
                //...
            };
            callback();
    
    0 讨论(0)
  • 2020-11-21 05:27

    I found simple way, it using shift()

    function waitReq(id)
    {
      jQuery.ajax(
      {
        type: 'POST',
        url: ajaxurl,
        data:
        {
          "page": id
        },
        success: function(resp)
        {
          ...........
          // check array length if not "0" continue to use next array value
          if(ids.length)
          {
            waitReq(ids.shift()); // 2
          )
        },
        error: function(resp)
        {
          ....................
          if(ids.length)
          {
            waitReq(ids.shift());
          )
        }
      });
    }
    
    var ids = [1, 2, 3, 4, 5];    
    // shift() = delete first array value (then print)
    waitReq(ids.shift()); // print 1
    
    0 讨论(0)
  • 2020-11-21 05:29

    On the basis of @BBonifield answer, I wrote a utility function so that semaphore logic is not spread in all the ajax calls.

    untilAjax is the utility function which invokes a callback function when all the ajaxCalls are completed.

    ajaxObjs is a array of ajax setting objects [http://api.jquery.com/jQuery.ajax/].

    fn is callback function

    function untilAjax(ajaxObjs, fn) {
      if (!ajaxObjs || !fn) {
        return;
      }
      var ajaxCount = ajaxObjs.length,
        succ = null;
    
      for (var i = 0; i < ajaxObjs.length; i++) { //append logic to invoke callback function once all the ajax calls are completed, in success handler.
        succ = ajaxObjs[i]['success'];
        ajaxObjs[i]['success'] = function(data) { //modified success handler
          if (succ) {
            succ(data);
          }
          ajaxCount--;
          if (ajaxCount == 0) {
            fn(); //modify statement suitably if you want 'this' keyword to refer to another object
          }
        };
        $.ajax(ajaxObjs[i]); //make ajax call
        succ = null;
      };
    

    Example: doSomething function uses untilAjax.

    function doSomething() {
      // variable declarations
      untilAjax([{
        url: 'url2',
        dataType: 'json',
        success: function(data) {
          //do something with success data
        }
      }, {
        url: 'url1',
        dataType: 'json',
        success: function(data) {
          //do something with success data
        }
      }, {
        url: 'url2',
        dataType: 'json',
        success: function(response) {
          //do something with success data
        }
      }], function() {
        // logic after all the calls are completed.
      });
    }
    
    0 讨论(0)
  • 2020-11-21 05:29

    $.when doesn't work for me, callback(x) instead of return x worked as described here: https://stackoverflow.com/a/13455253/10357604

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

    Look at my solution:

    1.Insert this function (and variable) into your javascript file:

    var runFunctionQueue_callback;
    
    function runFunctionQueue(f, index, callback) {
    
      var next_index = index + 1
    
      if (callback !== undefined) runFunctionQueue_callback = callback;
    
      if (f[next_index] !== undefined) {
        console.log(index + ' Next function avalaible -> ' + next_index);
        $.ajax({
          type: 'GET',
          url: f[index].file,
          data: (f[index].data),
          complete: function() {
            runFunctionQueue(f, next_index);
          }
        });
      } else {
        console.log(index + ' Last function');
        $.ajax({
          type: 'GET',
          url: f[index].file,
          data: (f[index].data),
          async: false,
          complete: runFunctionQueue_callback
        });
      }
    }
    

    2.Buil an array with your requests, like this:

    var f = [
               {file: 'file_path', data: {action: 'action', data: 'any_data}},
               {file: 'file_path', data: {action: 'action', data: 'any_data}},
               {file: 'file_path', data: {action: 'action', data: 'any_data}},
               {file: 'file_path', data: {action: 'action', data: 'any_data}}
            ];
    

    3.Create callback function:

    function Function_callback() {
      alert('done');
    }
    

    4.Call the runFunctionQueue function with parameters:

    runFunctionQueue(f, 0, QuestionInsert_callback);
    // first parameter: array with requests data
    // second parameter: start from first request
    // third parameter: the callback function
    
    0 讨论(0)
提交回复
热议问题