Wait until all jQuery Ajax requests are done?

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

提交回复
热议问题