Search code examples
javascriptjquery.when

$.when().done() is firing the done function before when completes


I have a page like this:

$(document).ready(function() {
    $.when(ajaxcall1(),ajaxcall2(),ajaxcall3()).done(finalCall());
});

For some reason the finalCall() is firing simultaneous to the three calls surrounded by $.when().

I tried calling a reference to the finalCall() function as in:

$(document).ready(function() {
    $.when(ajaxcall1(),ajaxcall2(),ajaxcall3()).done(finalCall);
});

But even then, it still fires the function before the prior 3 complete.

NOTE: I am not including the functions here as they are not relevant. I just need to know why the finalCall() function would fire simultaneous to then $.when() functions.

Thank you.


Solution

  • $.when does not call your callback at all. You are doing it yourself:

    //                                                        vv
    $.when(ajaxcall1(),ajaxcall2(),ajaxcall3()).done(finalCall());
    //                                                        ^^
    

    Change that to

    $.when(ajaxcall1(),ajaxcall2(),ajaxcall3()).then(finalCall);
    

    where the function is actually passed into the promise method, and it'll work (assuming your ajax functions return promises).