jQuery Deferred:$ .when()包含多个对象

cam*_*ari 8 jquery promise deferred .when

我需要一种方法来使用回调来获取不同的脚本.这种方法可行:

fetchScripts:function() {
    var _this=this;
    $.when(
        $.ajax({
            url:_this.url + 'library/script-one.js',
            type:'get',
            cache:true
        }),
        $.ajax({
            url:_this.url + 'library/script-two.js',
            type:'get',
            cache:true
        }),
        { .... },
        $.ajax({
            url:_this.url + 'library/script-n.js',
            type:'get',
            cache:true
        })
    ).then(function() {
        console.log('fetch is done');

    })
},
Run Code Online (Sandbox Code Playgroud)

但我想更加概括该方法,因为冗余正在增加.是否有可能将承诺传递给$ .when()?低于我的第一次尝试 - 但是网址总是相同的,即'script-n.js'也许我错过了这一点,你可以说明一个更"美"的解决方案

fetchScripts:function() {
    this.deferred=new $.Deferred();
    this.promise=this.deferred.promise();
    var _this=this;
    $.each([
        'script-one.js',
        'script-two.js',
        ( .... ),
        'script-n.js'
    ],function() {
        _this.script=this;
        _this.promise.then(function(){
            return $.ajax({
                url:_this.url + 'library/' + _this.script,
                type:'get',
                cache:true
            })
        });
    });
    $.when(
        this.promise
    ).then(function() {
        console.log('fetch is done');

    });
    this.deferred.resolve();
},
Run Code Online (Sandbox Code Playgroud)

Daf*_*aff 28

你还需要$ .when.但是,创建一个Deferreds(或promises)数组,然后其应用于$ .when:

fetchScripts:function() {
    var base = this.url;
    var defaults = {
        type:'get',
        cache:true
    };

    var libraries = [
        'library/script-one.js',
        'library/script-two.js',
        'library/script-n.js'
    ];

    var deferreds = $.map(libraries, function(current) {
        var ajaxOptions = $.extend({ url:  base + current }, defaults);
        return $.ajax(ajaxOptions);
    });

    $.when.apply($, deferreds).then(function() {
        console.log('All done');
    });
}
Run Code Online (Sandbox Code Playgroud)

或者扩展默认设置,您可以使用$ .ajax(默认值).