Search code examples
javascriptjqueryjquery-callback

jquery execute function when two conditions are met


I need to execute a specific function mvFinishItUp() when two conditions are met. More specifically, one condition is the callback success of a $.ajax the other is a normal flow of the code until it reaches the function. Kinda of this:

$.ajax({
    url: mv_finalUrl,
    success: function (data) {
        mvFinishItUp(data);
    },
    dataType: 'html'
});

/* here a lot more code, with animations and some delays */

mvFinishItUp(data) {
    /* My function code */
    /* But this code must only run after it has been called via the call back
       and after all the other code has been ran as well */
}

So, the function must wait for all the code if the ajax callback is quicker, or the other way around. Any ideas on how this could be implemented?

I'm willing to change the whole concept of script code, as I believe the loose code between the ajax, and the function itself should go to a function aswell ...


Solution

  • This is a perfect use case for jQuery Deferred objects.

    Remove the success: parameter from the AJAX call, and register the handler later:

    var jqxhr = $.ajax(...); 
    
    // do some other synchronous stuff
    ...
    
    // and *then* register the callback
    jqxhr.done(mvFinishItUp);
    

    Deferred objects cope perfectly well (by design) with being registered on an AJAX event after that event already finished.