xrDDDD
xrDDDD

Reputation: 583

How to get (facebook)variable from inside the function

I want the response.id outside of the function in another variable. That's all but I can't seem to get it to work. I tried at least 12 other ways of doing this. It's always "undefined".

However when I uncomment the alert inside the function I do get to see the response.id in the popup alert.

var a;  

function GetMyId() {  
    FB.api("/me",  
        function (response) {  
            a = response.id;  
            //return alert(response.id);  
            return;  
    });  
}  

a = GetMyId();  
alert(a);

Upvotes: 1

Views: 1429

Answers (1)

hugomg
hugomg

Reputation: 69954

Being restricted to putting the continuation inside a callback function is a price you have to pay in Javascript to be able to do assynchronous code. In your example, you could have your original function continue on doing other requests and stuff with the callback still being correctly called after FB responds, as soon as the event loop has free time for it.

The biggest point to notice about this callback stuff is that you unfortunately have to rewrite your code in continuation-passing-style. This means that your (async) functions (like the FB one) never return a value but instead receive a callback to call when they have a value to "return"

function getMyId(callback){
    //instead of returning an id, pass it to a
    //continuation function when we finally get it

    PB.api("/me", function(response){
        callback(response.id);
    });
}

function main(){
    getMyId(function(id){
        console.log("I can get my id", id)
    });
}

This is basically equivalent to the following non-cps code that you may be more used to (but can't use in this case)

function main(){
    var id = getMyId();
    console.log("i can get my id", id);
}

Theoretical curiosity: Function arguments are also variables. You can actually never use a var statement by abusing function arguments intead :)

var a = 17;
console.log('a is', a);

becomes

 (function(a){
    console.log('a is', a);
 }(17));

Upvotes: 2

Related Questions