Dealing with Arrays of Deferred Objects

前端 未结 3 883
情书的邮戳
情书的邮戳 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 03:13

    A more elegant way to write this example is with the array map function (or jQuery's $.map):

    var urls = [ 'foo.com', 'bar.com', 'baz.com', 'qux.com' ];
    
    var defers = urls.map( function( url) {
        return $.ajax({
            url: 'http://' + url
        });
    });
    
    $.when.apply(window, defers).done(function(){
        // Do Something
    });
    

    You could even roll your own "whenDone" and "fetchURL" functions:

    Array.prototype.whenDone = function(callback){
        return $.when.apply(window, this).done(callback);
    }
    
    function fetchURL(url){
        return $.ajax({
            url: 'http://' + url
        });
    }
    
    var urls = [ 'foo.com', 'bar.com', 'baz.com', 'qux.com' ];    
    
    urls.map( fetchUrl ).whenDone(function(){
        // Do Something
    });
    

提交回复
热议问题