Facebook API, Javascript SDK & variable scope
I've got a problem of variable scope with this code:
var likesString = "";
var getLikes = function() {
friend_ids = ["me", "123456789", "0987654321"];
likesString = "";
var likesArray = new Array();
var i = 0;
for (i = 0; i < friend_ids.length; i++) {
FB.api('/'+ friend_ids[i] +'/likes', function(response) {
var tmpLikesString = "";
if (response.data) {
likes = response.data;
var j = 0;
for (j = 0; j < likes.length; j++) {
if (likes[j]["category"] == "Movie") {
tmpLikesString = likes[j]["id"];
}
}
} else {
console.log("Error lookin开发者_Python百科g for likes");
}
likesArray.push(tmpLikesString);
console.log('In FB.api:'+ likesArray);
});
console.log('Out FB.api:'+ likesArray);
}
likesString = likesArray.join(',');
console.log("likes : " + likesString);
};
Inside FB.api, my var "likesArray" works, but when I'm out of it, it's like nothing happen to it…
The output if it can help to understand:
In FB.api:
In FB.api:,
In FB.api:,,
In FB.api:,,,208509052512525
In FB.api:,,,208509052512525,
In FB.api:,,,208509052512525,,153960391321494
(3)Out FB.api:
likes :
Thank you.
I don't think you have a scope issue, I think you have a timing issue.
I expect that the FB.api
call is asynchronous, am I right? (I haven't done any any Facebook programming.) That means that code after your FB.api
call will run before code within the callback you're giving FB.api
. But you're using likesArray
in the code following the call, when it will still be empty.
It's like doing this:
var a = 1;
setTimeout(function() {
a = 2;
}, 10);
alert(a); // alerts "1"
...because that, too, is asynchronous. You'll need to change your logic so that the code you currently have in the getLikes
function after the FB.api
call is instead called when the FB.api
function calls your callback.
Again using the simplified example for clarity, basically, the equivalent of moving the alert
:
var a = 1;
setTimeout(function() {
a = 2;
alert(a); // alerts "2"
}, 10);
Yes because it has the scope of that function. So you need to reurn it so that it can be accessed
oahuLikesString = likesArray.join(',');
console.log("likes : " + likesString);
return likesArray;
};
var likesArray = getLikes();
精彩评论