Is there a way to continue after one deferred fails?

…衆ロ難τιáo~ 提交于 2019-12-02 04:51:52

问题


I'm handling an unknown number of ajax requests. The request could fail in a 404. This causes the whole chain to fail.

Is there a way to continue after one deferred fails?

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

回答1:


You have to create your own deferred object, waiting for the other deferred to succeed or fail.

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

In that case your deferred will always be resolved.




回答2:


How about doing this way!

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


来源:https://stackoverflow.com/questions/12075074/is-there-a-way-to-continue-after-one-deferred-fails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!