2012-11-20 23 views
0

我是新來的JavaScript和jquery,我正在學習如何使用jquery的Deferred對象來執行一個動作之前等待循環完成。循環內的函數不需要以任何特殊順序調用。換句話說,函數n不依賴於函數n-1的結果,所以我不用管子把它們連在一起。當編程參數構造jquery的延期對象

到目前爲止,我有這個,它的工作原理:

// wait some random amount of time, then log a message 
// and resolve the Deferred object 
function doTask(id) { 
    var defer = $.Deferred(); 
    setTimeout(function() { 
    console.log(id + " finished!"); 
    defer.resolve(id); 
    }, Math.random()*1000); 
    return defer.promise(); 
} 

// log when these three independent tasks complete 
$.when(doTask("foo1"), doTask("foo2"), doTask("foo3")).done(function() { 
    console.log(" ... all done in no particular order!"); 
}); 

但我想構建參數列表。當$編程。我怎麼做?

回答

2

創建一個數組並將其應用於$.when

var defArr = []; 

defArr.push(doTask("foo1")); 
defArr.push(doTask("foo2")); 
defArr.push(doTask("foo3")); 

$.when.apply(null,defArr).done(function(){ 
    console.log(" ... all done in no particular order!"); 
}); 
+0

工程就像一個魅力!真棒! – Polly