多个异步ajax调用:即使有些失败,如何在所有调用解析后执行函数?

时间:2017-10-16 05:17:57

标签: javascript jquery ajax

假设我有一组像这样的ajax调用:

// an array of ajax calls
var callsArray = [];
callsArray.push(
  $.ajax({
    url: '/url1';
    cache: false,
    dataType: 'html'
  }),
  $.ajax({
    url: '/url2';
    cache: false,
    dataType: 'html'
  })
)

我事先知道这两个电话中至少有一个会失败。我希望在BOTH调用解析成功或失败后执行一个函数,我还想记录任何失败。

这不起作用:

// NOT APPROPRIATE
var errors = '';
$.when.apply(null, callsArray)
  .done(function() {
     console.log('Both calls completed but these urls failed: ' + errors);
  })
  .fail(function() {
     errors += this.url + ' ';
  })

上面的问题是.fail即使一次调用失败也会执行,而.done只有在零调用失败时执行。此外,我不能使用.always,因为它会在任何调用解析后立即执行。

因此我正在寻找类似的东西:

// FANTASY CODE
var errors = '';
$.when.apply(null, callsArray)
  .allCallsResolved(function() {
     // this executes only when all calls have
     // returned either a success or a failure
     // rather than when all calls succeed
     console.log('All calls completed but these urls failed: ' + errors);
  })
  .everyFailure(function() {
     // this executes every time a call fails
     // rather than as soon as any call fails 
     errors += this.url + ' ';
  })

3 个答案:

答案 0 :(得分:1)

您可以将每个ajax调用包装在一个解决成功和失败的Promise中,然后使用Promise.all来验证所有调用是否已完成和/或失败:

const promises = callsArray.map(function(call) {
    return new Promise(function(resolve, reject) {
        call.done(resolve).fail(function(error) {
            console.log(error);
            resolve(error);
        });
    });
});

Promise.all(promises).then(function(values) {
     console.log(values);
     //all calls done or failed
});

答案 1 :(得分:0)

var callsArray = [];
callsArray.push(
  $.ajax({
    url: 'https://httpbin.org/status/404',
    cache: false,
    dataType: 'html'
  }),
  $.ajax({
    url: 'https://httpbin.org/status/200',
    cache: false,
    dataType: 'html'
  })
);

callsArray.forEach((e) => {
  e.done(() => console.log('done'))
    .fail(() => console.log('fail'))
  });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

答案 2 :(得分:-1)

我在Jquery中使用延迟函数做了很久。

     var diff_array = [];
        var count=0;//you may use counter to know how many Deferred objects are resolved/rejected.

        //Iterate your callsArray 

        for(i in callsArray){

        diff_array[i] = $.Deferred();
        //execute each ajax
        //if ajax fails call reject else resolve/promise.
        diff_array[i].resolve();
        //count++ based on resolve/reject
        }

        //any where in the script
        // write deferred.done() which will be called immediately on resolving corresponding deferred object.
        diff_array[13].done(
        function() {
        .
        .
          if(count=callsArray.length){
           callFinalFunction();
           }
        }
        );