Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dealing with Arrays of Deferred Objects

Since using $.Deferred I've run into this scenario a couple times: I have a list of values each of which yields a Deferred Object in some way and I want to execute a callback once all of the Deferred Objects are resolved.

A more concrete example would be something like this:

var urls = [ 'foo.com', 'bar.com', 'baz.com', 'qux.com' ],
    defers = [], defer;

for( var i = 0, j = urls.length; i < j; i++ ){
    defer = $.ajax({
        url: 'http://' + urls[ i ]
    });

    defers.push(defer);
}

$.when.apply(window, defers).done(function(){
    // Do Something
});

Is there a more elegant solution than the code in my example?

like image 941
Jeff Rose Avatar asked Nov 03 '11 21:11

Jeff Rose


1 Answers

Yes there is, you should never reference a lookup value in a loop. Always make a copy.

var urls = [ 'foo.com', 'bar.com', 'baz.com', 'qux.com' ],
    defers = [], defer;

var urlsLength = urls.length;
for( var i = 0, j = urlsLength; i < j; i++ ){
    defer = $.ajax({
        url: 'http://' + urls[ i ]
    });

    defers.push(defer);
}

$.when.apply(window, defers).done(function(){
    // Do Something
});

But seriously, I'm just joshin' you. That code rocks. Stick with it.

like image 194
Sinetheta Avatar answered Oct 09 '22 08:10

Sinetheta