链排队回调结果

Chain queuing callbacks results

本文关键字:结果 回调 排队      更新时间:2023-09-26

我得到了这样的循环:

for ( var current in all )
{
    //load the item
    prepare.load( all[current].resource , function( result ) { 
         doSomethingWithResult(result);
    });
}
function AllItemsLoaded()
{
}

我的目标是在加载所有项目并执行回调中的代码之后执行AllItemsLoaded(),例如,对于每个项目回调都应该被调用,并且DoSomethingWithResult()应该在调用AllItemsLoadd()之前执行,所有这些项目都是异步加载的。

我尝试过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);

延迟是个好主意。然而,你需要等待承诺。以下是一种方法,用于在不按顺序执行的情况下等待所有承诺:

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()等待所有加载。

这就是您需要的吗?

发件人:http://aabs.wordpress.com/2009/12/16/sequential-script-loading-on-demand/

function LoadScriptsSequentially(scriptUrls, callback)
{
    if (typeof scriptUrls == 'undefined') throw "Argument Error: URL array is unusable";
    if (scriptUrls.length == 0 && typeof callback == 'function') callback();
    $.getScript(scriptUrls.shift(), function() { LoadScriptsSequentially(scriptUrls, callback); });
}

我会这样处理它(如下),用自己的异步对象替换每个$.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(即promise),这正是您想要的。

接下来是提供一个数组,在其中累积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);