$.when.done callback isn't working

2019-04-15 18:06发布

The following code has a bad syntax error. Probably because I'm using 'for' or something.

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

I'm trying to call couple of scripts and then when trey are all loaded I want to an alert to show.

2条回答
仙女界的扛把子
2楼-- · 2019-04-15 18:58

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.

查看更多
甜甜的少女心
3楼-- · 2019-04-15 19:01

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");
});
查看更多
登录 后发表回答