Possible Duplicate:
What does Asynchronous means in Ajax?
jQuery ajax return value
Trying to do a function that contains a jQuery function (getJson()) as part of it, but when I run it, my javascript function returns before calling the getJson(). I want to know why the getJson is not being called in order, and how to fix it.
function getUsers(screen_name){
user_list=[]
var id_list =[]
$.getJSON(url, function(json)
{
//do stuff here, I have breakpoint #1 here
});
return user_list //breakpoint #2 is here
}
When running it from the console: getUsers('myUser') it firsts gets to breakpoint #2 and then to breakpoint #1.
getJSON()is asynchronous by default. That means that calling it just starts the operation and the rest of your javascript continues to run. Sometime later, the asynchronous operation finishes and the success handler is called with the returned data.Any code that needs access to the returned data must either be in the success handler or in a function that you call from the success handler. You cannot use an asynchronous function and just return the
user_listlike you are trying to.Instead, you will have to rethink how your code is organized so that the code that uses the
user_listis in the success handler or is called from the success handler.getJSON()can be set to be synchronous, but that is generally a bad way to program in javascript because it locks up the browser for the duration of the networking call which is generally a bad user experience. Instead, if you write the code properly to deal with it being aschronous, then the browsers stays completely interactive for the full duration of the ajax call.