有没有办法继续一个延缓失败后?(Is there a way to continue after o

2019-06-27 06:40发布

我处理未知数量的Ajax请求。 请求可能在404。这就导致整个链条失败失败。

有没有办法继续一个延缓失败后?

var deferreds = [];
// fill deferreds with a number of ajax requests.
$.when.apply($, deferreds)
 .done(function(){
     // handle done
 }).fail(function(){
     // handle fail
     // would like to fix/resolve the failed deferred and continue with the rest
 });

Answer 1:

你必须创建自己的递延对象,等待对方推迟到成功或失败。

var myDeferred = $.Deferred();
var origDeferred = $.ajax(...);
// if request is ok, i resolve my deferred
origDeferred.done(function() {
  myDeferred.resolve.apply(this, arguments);
});
// if request failed, i also resolve my deferred
origDeferred.fail(function() {
  myDeferred.resolve.apply(this, arguments);
});

在这种情况下,你的延期总是会解决的。



Answer 2:

如何做这样!

var defArr = []; // Array of Deferreds

var recur = function(){
  $.when.apply($, defArr).done(function(){
    // Only do what event, when all are done, fail or resolved
    $.get("/media.php?i=done");
  }).fail(function(oDef){
    // Remove fail def from defArr
    defArr.splice(defArr.indexOf(oDef), 1)
    // do it again with all defArr into $.when
    recur();
  });
}

recur();


文章来源: Is there a way to continue after one deferred fails?