Mefhisto1 Mefhisto1 - 7 months ago 19
Javascript Question

Jquery deferred not behaving as expected

I make 2 ajax calls. Second one should be called only when the first is finished:

var deferred = $.Deferred();

firstAjaxCall();

deferred.done(function () {
secondAjaxCall();
});

function firstAjaxCall() {
$.ajax({
url: '/SomeUrl',
type: 'POST',
success: function () {
deferred.resolve();
}
});
}

function secondAjaxCall() {
$.ajax({
url: '/SomeOtherUrl',
type: 'Get',
});
}


I also tried like this (jQuery deferreds)

$.when(firstAjaxCall()).done(function() {
secondAjaxCall();
});


but no luck.

Still, in the first example, sometimes the second call gets called first, sometimes it doesn't

In the first example the flow is like this:

firstAjaxCall();
secondAjaxCall();
deferred.resolve();


why is second call called first and before
deferred.resolve()
?

Answer

You have to actually return the Deferred from $.ajax to $.when to make that work

function firstAjaxCall() {
    return $.ajax({
        url  : '/SomeUrl',
        type : 'POST'
    });
}

function secondAjaxCall(data_from_first) {
    return $.ajax({
        url  : '/SomeOtherUrl',
        type : 'Get',
    });
}

firstAjaxCall().done(secondAjaxCall);
Comments