Missing variable value (JavaScript)

3

I have this class, but whenever I instantiate, and access the value of fb_firstName is 'undefined'. What am I doing wrong?

In the set method, setFb_firstName(firstName) , the value is correct, but at the time of returning with getFb_firstName() has no value.

  function User(sender) {
        var fb_firstName; 


        FB.api('/' + sender, 'get', {access_token: token.getPage_acess_token()}, function (response) {
            setFb_firstName(response.first_name);
        });
        function setFb_firstName(firstName) {
            fb_firstName = firstName;
        }
        ;

        this.getFb_firstName = function () {
            return fb_firstName;
        };
    }
    
asked by anonymous 10.05.2016 / 00:09

1 answer

2

You need to pass a callback function to run at the end of the request, otherwise you will have trouble assigning values asynchronously.

See an example:

var User = function() {
    var username;
    return {
        init: function(callback) {
            FB.init(... , function(response) {
                username = response. username;
                callback();
            });
        },
        getUsername: function() {
            return username;
        }
    }
};

var user = new User(),
    username;
user.init(function() {
    username = user.getUsername();
});
    
10.05.2016 / 01:17