JQuery $ .when () not working properly

I have three functions. One of them is an AJAX call, one is the callback function provided to this AJAX function, and the last is a completely independent function, waiting for the completion of the AJAX functions. The third function must remain completely independent of the AJAX function; it cannot be passed as a parameter to the AJAX function. My code is:

doAjaxStuff: function(callbackFunction){
     $.ajax(
          // do AJAX call
          // With the AJAX data, create HTML div elements 
          callbackFunction();
     )
}

callMeMaybe: function(data){
     //do stuff with the return data from the AJAX call
}

patientFunction: function(){
    $.when(this.doAjaxStuff).done(function(){
         alert("doAjaxStuff() has finished!");
         // do stuff to the created HTML div elements.
    });
}

But I never get a message when a message appears. The AJAX call and callback function succeeds, but the $ .when () function never starts. What happens in this code?

+4
source share
1 answer

when, ajax / doAjaxStuff:

doAjaxStuff: function(callbackFunction){
     return $.ajax(
          // do AJAX call
          callbackFunction();
     )
}

, , promises .

doAjaxStuff: function(){
     return $.ajax(
          // do AJAX call
     );
}

:

patientFunction: function(){
    var self = this;   // Need to retain a reference to this
    $.when(this.doAjaxStuff()).done(function(data){
         alert("doAjaxStuff() has finished!");
         // do stuff to the created HTML div elements.
         self.callMeMaybe(data);
    });
}
+8

All Articles