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

后端 未结 2 480
谎友^
谎友^ 2021-01-14 15:04

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:          


        
相关标签:
2条回答
  • 2021-01-14 15:40

    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')
    })
    
    0 讨论(0)
  • 2021-01-14 15:55

    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);
        }
      }
    });
    
    0 讨论(0)
提交回复
热议问题