0

I have the following code:

Main.User =  (function(){
    var currentUser = ''

    var get_current_user = function get_current_user(){


        Main.Mod.do_ajax('home/get_user_pnp_id','GET',function(data){


            currentUser =  data.username;


        },null);

        console.log(currentUser); //Doesn't work. It logs empty string.
        return currentUser;   
    }

    return {
        get_current_user : get_current_user,
    }
})();

The 3rd parameter from Main.Mod.do_ajax() is a callback success function from my ajax call. However I cannot set currentUser inside that callback function.

What seems to be the problem?

Tasos K.
  • 7,979
  • 7
  • 39
  • 63
iamjc015
  • 2,127
  • 6
  • 25
  • 61
  • 1
    I assume that `Main.Mod.do_ajax()` makes an async call so when you write the variable to the console the callback function has not executed yet. – Tasos K. Aug 09 '15 at 15:33
  • 1
    See also http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call and http://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron – Felix Kling Aug 09 '15 at 16:07
  • Thanks, guys. I thought at the first place that it's about scope but it seems that the asynchronous nature of javascript is the problem. What I did is just to track it every single seconds to know if the result has returned. Thanks to your answers. – iamjc015 Aug 09 '15 at 16:10

1 Answers1

1

It's because your callback hasn't been called yet when the assignment is made since the callback is asynchronous. See Ajax jquery async return value and http://node-tricks.com/return-response-ajax-call/

Community
  • 1
  • 1
Ruan Mendes
  • 90,375
  • 31
  • 153
  • 217