0

I'm doing a GET request with jQuery inside of a function and trying to set a variable declared earlier in that function with the result. However, it comes up as undefined. Am I missing the concept here? How can I make something like this work? Thanks.

function doSomething1() {
    var x;
    $.get( window.location.href, { q: 'stuff', q2: $('input').val() }, function(data){
        // value shows up 
        console.log(data);
        x = data;
    });
    return x;
}

function doSomething2() {
      // comes up as undefined.
      console.log(doSomething1());
}

doSomething2();
Nick
  • 417
  • 1
  • 4
  • 14
  • your return is been called before the response comes from your ajax call, once it's asynchronous . that's why your `x` is undefined – andrepaulo Feb 15 '17 at 19:25
  • I also tried putting the "return x" inside of the callback function. Seems like that would be logical, but didn't matter. I will take a look at the duplicate. Thanks! – Nick Feb 15 '17 at 19:31

1 Answers1

1

This is a fault of the asynchronous effect of $.get() requests. You are returning x before the get has a chance to do anything. It takes a while to wrap your head around async functions.

The order of events is as follows:

  1. doSomething2() calls doSomething1()
  2. doSomething1() defines x without a value begins the GET request, and returns undefined.
  3. doSomething2() logs the returned x value
  4. The GET request finishes and processes its success function
Gwellin
  • 484
  • 1
  • 4
  • 8
  • What is the reason for it not working when I put the return in the callback of the GET request? – Nick Feb 15 '17 at 19:34
  • If your function waited on the GET to finish before continuing, then there would be a delay. Your initiating function continues on as the GET request runs in parallel, and you have to prepare for when it finishes separately. You already use `console.log(data)` within the success function—that is where you should handle tasks requiring this data. – Gwellin Feb 15 '17 at 19:39
  • Thanks. That makes. So it looks like either I have to handle the data in the callback itself, or pass it into another function from within the callback that will handle it. – Nick Feb 15 '17 at 19:50