Ori Refael Ori Refael - 2 months ago 8
Javascript Question

$.when.done callback isn't working

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.

Answer

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