I need a little help in best practices around “control flow” within javascript. In the below example my updateUI function is not properly working because my saveData function has not yet completed.
function save(data){
saveData(data);
updateUI();
}
For a temporary fix, I did this
function save(data){
if(saveData(data)){
updateUI();
}
}
Update: Here is my saveData method
function saveData(data){
$.ajax({
url: url, // a variable, not important for this example
data: data,
type: "post",
dataType: "json",
success: function(data) { return true; },
error: function(e) {
console.log(e);
}
})
I feel like I should learn the “standard” way, if such one exists.
Assuming that
saveDatais calling an AJAX function (e.g.$.ajax), have it return the result of that AJAX function:and then use jQuery deferred chaining to update the UI:
It allows you to avoid ever having to pass callback functions into your
saveDatacall, which then allows you to completely separate your data saving logic from your UI logic.EDIT I’ve updated the code to show how you can include a default
failhandler also using deferred objects, but still return thepromiseso that you can handle your UI updating outside.