我有一个这样的循环:
for ( var current in all )
{
//load the item
prepare.load( all[current].resource , function( result ) {
doSomethingWithResult(result);
});
}
function AllItemsLoaded()
{
}
我的目标是在所有项目加载后执行 AllItemsLoaded() 并执行回调中的代码,例如对于每个项目回调应该被调用并且 DoSomethingWithResult() 应该在 AllItemsLoaded() 被调用之前执行,所有这些项目都是异步加载的.
我试过 Jquery Deferred/pipe,我的代码如下所示:
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);