2013-02-26 45 views
10

我正在尋找一種方式經過兩次的Ajax調用做一個回調完成:jQuery的延遲 - 等待,直到兩個電話完全

$.when(
    call1(), 
    call2() 
).always(function() { 
    // Here I want to be sure the two calls are done and to get their responses 
); 

美中不足的是,其中一個呼叫可能會失敗。所以,在我的代碼中,總是會調用而不用等待另一個調用。

如何等待兩個呼叫完成(成功或失敗)?

+1

你可能想看看承諾http://api.jquery.com/promise/ – BlueBird 2013-02-26 15:41:02

+0

@BlueBird:怎麼樣?承諾需要我沒有的jquery對象。你可以添加一個例子嗎? – Naor 2013-02-26 15:47:38

+1

@BlueBird:'$ .when'已經返回一個承諾對象,即OP已經使用承諾。 – 2013-02-26 15:48:47

回答

11

這是應該做的伎倆:

$.whenAllDone = function() { 
    var deferreds = []; 
    var result = $.Deferred(); 

    $.each(arguments, function(i, current) { 
     var currentDeferred = $.Deferred(); 
     current.then(function() { 
      currentDeferred.resolve(false, arguments); 
     }, function() { 
      currentDeferred.resolve(true, arguments); 
     }); 
     deferreds.push(currentDeferred); 
    }); 

    $.when.apply($, deferreds).then(function() { 
     var failures = []; 
     var successes = []; 

     $.each(arguments, function(i, args) { 
      // If we resolved with `true` as the first parameter 
      // we have a failure, a success otherwise 
      var target = args[0] ? failures : successes; 
      var data = args[1]; 
      // Push either all arguments or the only one 
      target.push(data.length === 1 ? data[0] : args); 
     }); 

     if(failures.length) { 
      return result.reject.apply(result, failures); 
     } 

     return result.resolve.apply(result, successes); 
    }); 

    return result; 
} 

退房this Fiddle來看看它是如何工作的。

基本上它會等待所有延遲完成,無論它們是否失敗並收集所有結果。如果我們發生故障,則返回的延遲將失敗並顯示所有故障列表,並以其他方式成功解決。

+0

謝謝。我希望jQuery已經有這個解決方案。 – Naor 2013-02-26 16:35:29

+0

不是。我認爲更常見的情況是,如果其中任何一個失敗都不需要等待所有延遲完成。 – Daff 2013-02-26 16:56:20

+0

那麼,假定成功參數的順序與添加的延期順序相同,是否正確?來自dfd1的參數[0]? – DavidVdd 2013-10-22 09:10:34

1

這並不美觀,但您可以爲完成每個ajax調用設置一個全局「已完成」變量。每個調用還會檢查是否設置了這兩個變量,如果是,請調用您的always函數。

0

您也可以嵌套調用:

$.when(call1()).always(function(){ 
    $.when(call2()).always(function(){ 
     // Here I want to be sure the two calls are done and to get their responses 
    }); 
}); 

但是,當然,在這兩個電話將成爲同步到對方。