Is it possible to run code after all ajax call completed under the for loop statement?

情到浓时终转凉″ 提交于 2019-12-30 10:34:45

问题


I have a for loop statement, each loop will execute an ajax call.

$.each(arr, function(i, v) {
    var url = '/xml.php?id=' + v;
    $.ajax({
        url: url,
        type: 'GET',
        dataType: 'xml',
        success: function(xml) {
            if ($(xml).find('Lists').attr('total') == 1) {
                // some code here
            }
        },
        complete: function() {
            // some code here
        }
    })
})

I want to run code after all ajax call completed under the loop, I have tried to place the code below to last line, it is not executed when the ajax call completed

    if (i == arr.length - 1) {
        // some code here
    }

Therefore, if I have 10 times of loop, there are 10 times of ajax call. I want to run a code after there 10 times of ajax call completed, any ideas?

Is it better to use .ajaxComplete() or .done() to achieve it?

Thanks


回答1:


Try using $.when()

var arr = [];
$.each(arr, function(i, v) {
    var url = '/xml.php?id=' + v;
    var xhr = $.ajax({
        url: url,
        type: 'GET',
        dataType: 'xml',
        success: function(xml) {
            if ($(xml).find('Lists').attr('total') == 1) {
                // some code here
            }
        },
        complete: function() {
            // some code here
        }
    });
    arr.push(xhr);
})

$.when.apply($, arr).then(function(){
    console.log('do')
})



回答2:


I came across a similar scenario but inside the loop, the AJAX call was done in another function call (called fetchData).

so I made the fetchData function return a Promise coming from the AJAX call and I chained it using the then clause in order to process the response.

Here's the Plunker link

$(document).ready(function() {
  var message = '';

  process();

  function process() {
    var promises = [];
    for (var i = 0; i < 3; i++) {
      var promise;
      (function (index) {
        promise = fetchData(index).then(function (response) {
          // do something with the response.
          message += 'Iteration ' + index + '\n';
        });
      })(i);

      promises.push(promise);
    }

    $.when.apply($, promises).then(function () {
      // do something after all the AJAX calls are completed.
      alert(message);
    });
  }

  function fetchData(param) {
    return $.ajax('data.json')
      .success(fetchDataSuccess)
      .error(fetchDataFailed);

    function fetchDataSuccess(response) {
      return response;
    }

    function fetchDataFailed(error) {
      console.error(error);
    }
  }
});


来源:https://stackoverflow.com/questions/16956116/is-it-possible-to-run-code-after-all-ajax-call-completed-under-the-for-loop-stat

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!