Javascript 链队列回调结果
我有一个这样的循环:Javascript 链队列回调结果,javascript,jquery,asynchronous,callback,promise,Javascript,Jquery,Asynchronous,Callback,Promise,我有一个这样的循环: for ( var current in all ) { //load the item prepare.load( all[current].resource , function( result ) { doSomethingWithResult(result); }); } function AllItemsLoaded() { } var chain = new $.Deferred().resolve(); for
for ( var current in all )
{
//load the item
prepare.load( all[current].resource , function( result ) {
doSomethingWithResult(result);
});
}
function AllItemsLoaded()
{
}
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);
我的目标是在加载所有项并执行回调中的代码后执行AllItemsLoaded(),例如,在调用AllItemsLoaded()之前,应该调用每个项的回调并执行DoSomethingWithResult(),所有这些项都是异步加载的
我尝试了Jquery/pipe,我的代码如下所示:
for ( var current in all )
{
//load the item
prepare.load( all[current].resource , function( result ) {
doSomethingWithResult(result);
});
}
function AllItemsLoaded()
{
}
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);
这是你需要的吗
发件人:
推迟是个好主意。然而,你需要等待承诺。以下是一种方法,它使用的是在不按顺序履行承诺的情况下等待所有承诺的时间:
var loads = [];
for ( var current in all )
{
(function(){
var deferred = new $.Deferred();
prepare.load( all[current].resource , function( result ) {
doSomethingWithResult(result);
deferred.resolve(result);
});
loads.push(deferred.promise());
})();
}
$.when.apply(null, loads).then(AllItemsLoaded);
首先为每个加载创建一个新的延迟。将它的承诺放在一个集合中。加载后,解决延迟的问题。使用$.when()等待所有加载。我会这样处理它(如下所示),在这里,您使用自己的异步对象替换每个
$.get()
,并使用它自己的完整处理程序
$(document).ready(function() {
$.when(
$.get("ajax.php?a=b"),
$.get("ajax.php?a=c"),
$.get("ajax.php?a=d")
).then(
function() {
// both AJAX calls have succeeded
alert("All Done");
},
function() {
// one of the AJAX calls has failed
alert("One or more failed");
}
);
});
第一件事是使用
.get()
或.post()
而不是.load()
,原因是.load()
返回jQuery,而另外两个返回jqXHR(即承诺),这正是您在这里想要的
下一步是提供一个数组,在其中积累jqXHR承诺
最后,您需要知道如何获取$.when()
来执行承诺数组,以及在所有承诺都已解决(或发生错误)时执行某些操作
整个事情看起来是这样的:
var promises = [];//new Array
for ( var current in all ) {
prepare.get( all[current].resource, function( result ) {
doSomethingWithResult(result);
});
}
$.when.apply(null, promises).then(AllItemsLoaded, myErrorHandler);
我最喜欢你的答案,但我有个问题。AllItemsLoaded在调用resolve()之前立即执行。@Deepsy我现在不在计算机旁,但我想什么时候不需要数组。我应该用$.when.apply。我到电脑前会试试的。@Deepsy看起来应用不是唯一的问题。我还需要创建一个新的作用域,这样延迟变量就不会被共享。这是小提琴:现在很好用,谢谢。向上投票并将其标记为已回答。