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

后端 未结 2 502
谎友^
谎友^ 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条回答
  •  萌比男神i
    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);
        }
      }
    });
    

提交回复
热议问题