1

私はこのようなループを得ました:

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

function AllItemsLoaded()
{
}

私の目標は、すべてのアイテムがロードされ、コールバック内のコードが実行された後に 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);
4

4 に答える 4

2

延期は良い考えです。ただし、約束を待つ必要があります。次に示すのは、すべての promise を順番どおりに実行せずに待機する when を使用する方法です。

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);

まず、ロードごとに新しい deferred を作成します。その約束をコレクションに置きます。ロード後、据え置きを解決します。$.when() ですべてのロードを待機します。

于 2013-06-30T01:37:59.267 に答える
1

これはあなたが必要とするものですか?

から: 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); });
}
于 2013-06-30T01:23:03.480 に答える
0

それぞれ$.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");
        }
    );
});
于 2013-06-30T01:41:39.380 に答える
0

まず、使用する.get()かし.post()ないか.load()です。その理由は、.load()jQuery を返し、他の 2 つは jqXHR (つまり、promise) を返すためです。これは、ここで必要なものです。

次は、jqXHR promise を蓄積するための配列を提供することです。

$.when()最後に、promise の配列に基づいて行動する方法、それらすべてが解決された (またはエラーが発生した) ときに何かを行う方法を知る必要があります。

全体は次のようになります。

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);
于 2013-06-30T01:45:28.423 に答える