$.when.done callback isn't working

被刻印的时光 ゝ 提交于 2019-12-04 18:39:39

A commented (but untested) solution with the changes is below

// 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' );
});

If you have the option, something much simpler is just

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

If I understand correctly, the code to do what you want can be written concisely with $.map() and $.when.apply(), as follows :

// 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");
});

Note: $.when.apply(null, promises) is equivalent to :

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

where jqXHR0 etc. are jqXHR objects returned by five $.getScript() calls.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!