延期失败后有没有办法继续?

时间:2012-08-22 14:12:58

标签: javascript jquery ajax jquery-deferred

我正在处理未知数量的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
 });

2 个答案:

答案 0 :(得分:2)

您必须创建自己的延迟对象,等待其他延迟成功或失败。

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);
});

在这种情况下,您的延期将始终得到解决。

答案 1 :(得分:0)

这样做怎么样!

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();