3

只是想知道在我开始破解我的代码之前。例如:

if (blahblah) {
  $.ajax("randomthingy1");
}
if (blahblahblah) {
  $.ajax("randomthingy2");
}
// Use jQuery to test when they've both finished. Obviously they won't always both finish, as they might not both exist, and none of them might exist either.

$.when($.ajax("randomthingy1"), $.ajax("randomthingy2"), function (stuff) {
  // foo
}

// Might produce an error, as one might not exist. But will it move on and not bother?

就是想。如果它确实会产生错误并停止执行,有没有办法捕捉错误并继续?

4

3 回答 3

2

.when()done() handler如果您传入的所有Defered对象都可以解决,则只会触发。因此,在您的实例中,如果一个Ajax 请求由于某种原因失败,则混合的Defered对象将解析为失败,并且您绑定的处理程序.when() -> done将不会触发。但当然,在这种情况下,您的所有处理程序都绑定failalways将触发。

$.when( $.ajax({}), $.ajax({}) )
   .done(function() {
      // all promises (ajax requests) resolved successfully
   })
   .fail(function() {
      // at least one promise (ajax request) failed
   })
   .always(function() {
      // will always get fired
   });

http://api.jquery.com/category/deferred-object/

于 2012-10-26T13:15:01.030 回答
1

我不确定这是否能回答您的问题,但这是我处理此类事情的方式:

var requests = [];
if (blahblah) {
  requests.push( $.ajax("randomthingy1") );
}
if (blahblahblah) {
  requests.push( $.ajax("randomthingy2") );
}
$.when.apply( $, requests ).then( function( ) {
  // handle success
}, function( ) {
  // handle error
});

这确保即使这些条件都不满足,即不存在请求,代码也会进入处理程序。

于 2012-10-26T13:17:42.900 回答
0

您可以使用此布局来确保始终响应延迟完成,无论是否已解决或拒绝:

$.when(deferred1, deferred2, ...)
    .done(function (data1, data2, ...) {
        // success handlers - fires if all deferreds resolve
    })
    .fail(function (error1, error2, ...) {
        // failure handlers - fires if one or more deferreds reject or throw exceptions
    })
    .always(function () {
        // complete handlers - always fires after done or fail
    });
于 2012-10-26T13:22:43.683 回答