Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery $.when() not working as expected

I have three functions. One is an AJAX call, one is a callback function given to this AJAX function, and the last one is a completely independent function that waits for the AJAX functions to finish. The third function has to remain completely independent from the AJAX function, it can not be passed as a parameter to the AJAX function. My code:

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 the alert message to show up. The AJAX call and callback function are performed succesfully, but the $.when() function is never triggered. What is going wrong in this code?

like image 459
yesman Avatar asked Feb 12 '23 20:02

yesman


1 Answers

To use when you need to return the ajax deferred/promise from your doAjaxStuff method:

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

As you mention, the callback needs to be supplied with the current syntax, but with promises you no longer need callbacks.

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

Call with:

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);
    });
}
like image 169
Gone Coding Avatar answered Feb 14 '23 09:02

Gone Coding