在多次 ajax 调用后执行函数

Execute function after multiple ajax calls

我想在多个 ajax 调用完成时触发一个函数。 经过一些研究,我发现了 jquery $.when 函数。 我测试了这个功能,但它不起作用。 有人知道如何解决这个问题吗?

var root = 'http://jsonplaceholder.typicode.com';

$(function(){
    restCall.ajaxcalls();
})

var restCall =
{
    ajaxcalls: function(){
        $.when(this.getAlbums(), this.getPhotos()).done(function(fetchedAlbums,fetchedPhotos){
            console.log(fetchedAlbums);
            console.log(fetchedPhotos);
        });
    },

    getAlbums:function() {
        $.ajax({
            type: 'GET',
            url: root + '/albums'
        }).done(function(response){
            return response;
        }).fail(this.ajaxFail);
    },

    getPhotos: function(){
        $.ajax({
            type: 'GET',
            url: root + '/photos'
        }).done(function(response){
            return response;
        }).fail(this.ajaxFail);
    },

     ajaxFail: function(xhr,message,error){
        console.log("het liep mis met de ajax call",xhr,message,error);
    }
};

控制台记录 returns 未定义,但我想要 ajax 调用获取的对象。

有没有人看出哪里出了问题?

您永远不应该尝试 return .done() 处理程序中的值,因为它是一个异步调用。相反,return 由您的 ajax 调用 return 承诺,并像这样在该结果上使用您的 $.when()

getAlbums: function() {
    return $.ajax({
        type: 'GET',
        url: root + '/albums'
    }).fail(this.ajaxFail);
},
getPhotos: function(){
    return $.ajax({
        type: 'GET',
        url: root + '/photos'
    }).fail(this.ajaxFail);
}