2012-09-28 36 views
1

我需要的是將.pipe()調用的未知數(僅在運行時已知)添加到由jQuery的.when()監視的函數中。這些調用將基於由另一個異步操作產生的ajax調用。請參閱下面的代碼以獲得更加清晰的解釋:延遲jQuery - 在運行時向延遲合同添加回調

$.when(
    $.ajax({ 
     async: true,   
     success: function (data, textStatus, jqXhr) { 
      console.log('Level 1') 

      for(var i = 0; i < data.length; i++) 
       jqXhr.pipe(
        $.ajax({ 
         data: data[i],                
         async: true,   
         success: function (data, textStatus, jqXhr) { 
          console.log('Level 2'); 
         },  
        }) 
       ); 
     },  
    }), 
    $.ajax({ 
     async: true,   
     success: function (data, textStatus, jqXhr) { 
      console.log('Level 3'); 
     },  
    }) 
).done(function(){ console.log('All done!'); }); 

基本上1級和3級需要並行執行。 Level 2s都是基於Level 1的結果。Level 1,所有Level 2和Level 3都需要在全部完成之前執行。

使用上面的代碼不起作用,因爲對.pipe()的調用不影響.when()監視的內容。

是否有可能做我想用jQuery的Deferred框架?

感謝您的任何幫助。

注意:早些時候,我問了一個非常類似的問題,但我意識到情況比我在那裏說明的複雜得多,我不想引起與現有答案的混淆。

Original question

回答

1

這並不是說要複雜得多。如果要並行執行所有2級呼叫,只需調用$.when.pipe回調中並返回延期對象:

$.when(
    $.ajax({   
     // ...  
    }).pipe(function(data) { 
     // concise way to make the Ajax calls for each value 
     var deferreds = $.map(data, function(value) { 
      return $.ajax({data: value, /*...*/}); 
     }); 
     return $.when.apply($, deferreds); 
    }), 
    $.ajax({   
     // ...  
    }) 
).done(function(){ console.log('All done!'); }); 

如果要依次執行它們,再次使用.pipe

$.when(
    $.ajax({   
     // ...  
    }).pipe(function(data) { 
     // A "dummy" resolved deferred object 
     var deferred = (new $.Deferred()).resolve(); 
     $.each(data, function(value) { 
      deferred = deferred.pipe(function() { 
       return $.ajax({data: value, /*...*/}); 
      }); 
     }); 
     return deferred; 
    }), 
    $.ajax({   
     // ...  
    }) 
).done(function(){ console.log('All done!'); }); 

我不得不說,儘管你應該把Ajax調用的數量降到最低。