Dealing with Arrays of Deferred Objects

前端 未结 3 884
情书的邮戳
情书的邮戳 2021-02-09 02:56

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

3条回答
  •  暖寄归人
    2021-02-09 02:56

    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.

提交回复
热议问题