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?

1 Answer 1

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);
}
Sign up to request clarification or add additional context in comments.

2 Comments

Returned function must be deferred function or promise compatible returned value. Where it must resolved or reject on resolution.
@wajatimur jQuery's $.ajax() function returns a promise that is automatically resolved or rejected by jQuery.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.