Here's some pseudo code that I'm working with (and where'd I'd typically use async: false;
):
function getData(){
var obj = {};
if(!settings.data){
$.ajax({
url: '/someendpoint',
async: false,
success: function(data){
obj = data;
}
});
} else {
obj = settings.data;
}
return obj;
}
So we have a function that returns an object. Now if we already have some data, we just assign this data, but if we don't, we need to request the data from the server. A time to use async: false
? Because we need to halt execution as to grab the data before we return the obj?
I deal with this concept time and time again, resorting to async: false
most times. Can someone outline a better approach please?
Here's some pseudo code that I'm working with (and where'd I'd typically use async: false;
):
function getData(){
var obj = {};
if(!settings.data){
$.ajax({
url: '/someendpoint',
async: false,
success: function(data){
obj = data;
}
});
} else {
obj = settings.data;
}
return obj;
}
So we have a function that returns an object. Now if we already have some data, we just assign this data, but if we don't, we need to request the data from the server. A time to use async: false
? Because we need to halt execution as to grab the data before we return the obj?
I deal with this concept time and time again, resorting to async: false
most times. Can someone outline a better approach please?
2 Answers
Reset to default 8Embrace the asynchronous nature of the web. Granted, it's paradigm shift, but so was multi-threading back in the day and in my opinion the way it's handled now in jQuery with Deferred objects makes it preferable over multi-threading. It's the reason why Node.js is being so popular.
Don't just use callback functions as you might read on the web or in other answers. Learn about Deferred and Promise objects, and instead of returning the data, return a promise that you can use to attach behavior to when that promise is 'resolved'.
function getData(){
var obj;
if(!settings.data){
obj = $.get('/someendpoint');
} else {
obj = $.when(settings.data);
}
return obj;
}
Then, the caller can use this data the moment it bees available, as such:
var promise = getData();
promise.done(function (data) {
// Do something with the data.
});
It will feel awkward at first, because you're no longer returning data but instead a 'promise' to that data, but after a while you'll just 'get it'. Trust me.
Use a simple callback mechanism
function getData(callback){
var obj = {};
if(!settings.data){
$.ajax({
url: '/someendpoint',
success: function(data){
callback(data)
}
});
} else {
callback(settings.data)
}
}
getData(function(data){
//do things which depends on data
})