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?

3
  • 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. Commented Aug 9, 2015 at 15:33
  • 1
    See also stackoverflow.com/questions/14220321/… and stackoverflow.com/questions/23667086/… Commented Aug 9, 2015 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. Commented Aug 9, 2015 at 16:10

1 Answer 1

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/

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.