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?
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);
});
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With