Simone Tolomelli
Simone Tolomelli

Reputation: 11

Cannot get FB.api response with js class

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);

Upvotes: 0

Views: 71

Answers (3)

Marco Amendola
Marco Amendola

Reputation: 1468

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);
});

Upvotes: 1

Umberto Di Lorenzo
Umberto Di Lorenzo

Reputation: 9

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); });

Upvotes: 0

Emidio Picariello
Emidio Picariello

Reputation: 21

try

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

and post here response value.

Upvotes: 0

Related Questions