-1

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.

Community
  • 1
  • 1
leonsas
  • 4,718
  • 6
  • 43
  • 70
  • `getJSON` is called in order, but it makes an Ajax request. – Felix Kling Jul 26 '12 at 20:58
  • There have to be several *dozen* versions of this question already asked and answered here on SO. – T.J. Crowder Jul 26 '12 at 20:59
  • But yet I couldn't find any. I'm deleting it – leonsas Jul 26 '12 at 21:00
  • I never ask a question without first searching a few minutes, and I usually find an exact duplicate of my question. In this case I didn't know what words I was even searching for. Yeah, searching for "async getjson return" or something gets at the answer fast, but I had no idea I was searching for the word async, which turned to be the key word. Thanks anyways. – leonsas Jul 26 '12 at 21:14

1 Answers1

2

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_list like you are trying to.

Instead, you will have to rethink how your code is organized so that the code that uses the user_list is 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.

jfriend00
  • 683,504
  • 96
  • 985
  • 979