2

I wanted to fire a function when multiple ajax calls are completed. After some research I found the jquery $.when function. I tested this function but it doesn't work. Does anybody know how to solve this?

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);
    }
};

The console logs returns undefined, but I want the objects that were fetched by the ajax call.

Does anybody see where it went wrong?

Y. Jacobs
  • 61
  • 6

1 Answers1

1

You should never try to return a value in a .done() handler, because it is an asynchronous call. Instead, return the promise returned by your ajax call, and use your $.when() on that result like so:

getAlbums: function() {
    return $.ajax({
        type: 'GET',
        url: root + '/albums'
    }).fail(this.ajaxFail);
},
getPhotos: function(){
    return $.ajax({
        type: 'GET',
        url: root + '/photos'
    }).fail(this.ajaxFail);
}
Dave
  • 10,748
  • 3
  • 43
  • 54
  • 1
    Returned function must be deferred function or promise compatible returned value. Where it must resolved or reject on resolution. – Azri Jamil Nov 30 '15 at 21:10
  • @wajatimur jQuery's `$.ajax()` function returns a promise that is automatically resolved or rejected by jQuery. – Dave Nov 30 '15 at 21:16