我有這樣一個循環:鏈排隊回調導致
for (var current in all)
{
//load the item
prepare.load(all[current].resource , function(result) {
doSomethingWithResult(result);
});
}
function AllItemsLoaded()
{
}
我的目標是以後所有項目加載並執行在回調的代碼,例如執行AllItemsLoaded()在調用AllItemsLoaded()之前,應該調用每個項目回調並執行DoSomethingWithResult(),所有這些項目都是異步加載的。
我試過jQuery的遞延/管,看起來像這樣我的代碼:
var chain = new $.Deferred().resolve();
for (var current in all)
{
chain = chain.pipe(function(res){
prepare.load(all[current].resource , function(result) {
doSomethingWithResult(result);
});
});
//if I do a return here, the pipe will continue without getting the result,
so I need to continue the pipe after load's callback and
doSomethingWithResult is executed
}
chain.done(AllItemsLoaded);
我喜歡你的答案最多的,但我有一個問題。在調用resolve()之前立即執行AllItemsLoaded。 – Deepsy
http://jsfiddle.net/5vcqQ/ <查看結果 – Deepsy
@Deepsy我現在不在電腦上,但是我想什麼時候不用數組。我應該使用$ .when.apply。當我到達電腦時我會嘗試它。 –