0

this is my code:

function User() {
    var self = this;

    FB.api(someurl, function (response) {

        self.id = response.id;

    });
}

I can't get the id going like this:

var user = new User();
console.log(user.id);

3 Answers 3

1

FB.api is an asynchronous function with a callback. At the time you read user.id the callback function has not been called yet.

Maybe you should move the async initialization out of the constructor, adding an explicit "init" function:

function User() {
    var self = this;

    this.init = function(onCompletion) {
        FB.api(someurl, function (response) {
            self.id = response.id;
            if (onCompletion) onCompletion();
        });
    }
}

var user = new User();
user.init(function(){
    console.log(user.id);
});
Sign up to request clarification or add additional context in comments.

2 Comments

Ok then, how would I do that? I just want to store response.id and response.email in order to use them several time without calling FB.login.
It's fine to store them for later use; you just have to be sure to not access those cached values before they are loaded. If you need them as soon as possible, use the init callback.
0

try

FB.api(someurl, function(response) {
  console.log(response);
});

and post here response value.

3 Comments

everything's fine with response. {name:"some name", email: "[email protected]", id:123456789}
so try: function User() { var self = this; self.id = 123456; } var user = new User(); console.log(user.id); what do you get?
123456. the problem is getting the value within FB.api
0

Try defining a pattern where you initialize your object, then using a callback in your asynchronous request. Something like this:

function User() {
    var self = this;
    self.init = function(cb) { 
        FB.api(someurl, function (response) {

            self.id = response.id;
            if (cb) { 
               cb();
            }
        });
    }
}

then

var user = new User();
user.init(function() { console.log(user.id); });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.