$ .when.done回调不起作用

时间:2013-06-09 08:02:24

标签: javascript jquery callback .when

以下代码的语法错误。可能是因为我正在使用'for'或其他东西。

$.when(
    for (var i=0; i < 5; i++) {
        $.getScript( "'" + someArr[i].fileName + ".js'");
    }
    $.Deferred(function( deferred ) {
              $( deferred.resolve );
    })
).done(function() {
    alert("done");
});

我正在尝试调用几个脚本,然后当trey全部加载时,我想要显示警报。

2 个答案:

答案 0 :(得分:4)

带有更改的评论(但未经测试)解决方案在

之下
// When takes a promise (or list of promises), not a random string of javascript
$.when((function() {
    // First we need to define a self resolving promise to chain to
    var d = $.Deferred().resolve();

    for ( var i = 0; i < 5; i++ ) {

        // Trap the variable i as n by closing it in a function
        (function(n) {

            // Redefine the promise as chaining to itself
            d = d.then(function() {

                // You can *return* a promise inside a then to insert it into
                // the chain. $.getScript (and all ajax methods) return promises
                return $.getScript( someArr[n].fileName + '.js' );
            });

        // Pass in i (becomes n)
        }(i));
    }

    return d;

// self execute our function, which will return d (a promise) to when
}())).then(function() {

    // Note the use of then for this function. done is called even if the script errors.
    console.log( 'done' );
});

如果你有选择权,那就更简单了

$.when(
    $.getScript( 'fileName1.js' ),
    $.getScript( 'fileName2.js' ),
    $.getScript( 'fileName3.js' ),
    $.getScript( 'fileName4.js' )
).then(function() {
    alert("done");
});

答案 1 :(得分:1)

如果我理解正确,可以使用$.map()$.when.apply()简明扼要地编写您想要的代码,如下所示:

// First scan someArr, calling $.getScript() and building 
// an array of up to 5 jqXHR promises.
var promises = $.map(someArr, function(obj, index) {
    return (index < 5) ? $.getScript(obj.fileName + ".js") : null;
});
// Now apply the promises to $.when()
$.when.apply(null, promises).done(function() {
    alert("done");
});

注意:$.when.apply(null, promises)相当于:

$.when(jqXHR0, jqXHR1, jqXHR2, jqXHR3, jqXHR4);

其中jqXHR0等是jqXHR次调用返回的$.getScript()个对象。