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オブジェクトが解決された場合にのみ起動します。したがって、あなたのインスタンスでは、何らかの理由で1つのAjaxリクエストが失敗した場合、混合されたDeferedオブジェクトは失敗するように解決され、バインドされたハンドラーは起動し.when() -> doneません。しかしもちろん、その場合、すべてのハンドラーがバインドされるfailか、起動しますalways

$.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 に答える