Possible Duplicate:
How can I get jQuery to perform a synchronous, rather than asynchronous, AJAX request?
how to wait for an ajax call to return
Hear me out. I completely understand this code segment.
$.getJSON(someURL, function(data){
//do something with my data
})
.success(function () {
//Call what you want on success
})
This seems fine if I just need to take one action that is pretty static. However, what if I want to be less restricted, for instance this
function my_func(){
$.getJSON(someURL, function(data){
//do something with my data... like modify an array or the dom
})
}
Now the driver
my_func();
//Now I want to call a function that relies on the data that my_func brought into the script.
Is there something wrong with the way I’m coding my script if I want to do it like this? Or am I just missing some awesome built in method?
I see two possible jQuery-ish ways there.
The first would be to use another callback that can be passed to
my_func:The second way would be to create a custom event that gets triggered inside
my_funcand can be listened to from the outside:I strongly recommend using
async: falseonly if it is absolutely necessary.Just another (very neat) way to deal with this is the jQuery.Deferred object:
Your function returns an object that allows to register callbacks. Within the function you then just need to make sure to call
resolveto invoke all registereddonecallback handlers.