I’m trying to get this function to set sortedScores to a value… whenever i do console.log anywhere it seems to store the values right, but it can’t actually set sortedScores properly…
function facebook(sortedfriends) {
var myID;
var access_token;
FB.init({
appId : something,
status : true,
cookie : true,
xfbml : true,
});
FB.getLoginStatus(function(response, sortedfriends) {
if(!response.session) {
FB.login(function(response) {
myId = response.session.uid;
access_token = response.session.access_token;
//does stuff
if (!response.session) {
console.log('User cancelled login or did not fully authorize.');
}
});
}
else if(response.session) {
myId = response.session.uid;
access_token = response.session.access_token;
var D = new Array();
this.access_token = access_token;
FB.api('/me/feed?access_token=' + access_token + '&limit=100', function(response, sortedfriends) {
for( i=0; i<response.data.length; i++) {
var msg = response.data[i];
D.push(msg);
}
sortedfriends = somefunction(D, myID);
//i know somefunction works because if i do console.log(sortedfriends) it shows me the right values...
});
}
});
}
when i try
var friends;
facebook(friends);
friends is just undefined… halp?
It is not clear where you are trying to access sortedfriends, but I’m guessing that your issue is that the Facebook login is asynchronous, so the response comes some time later after the
facebookfunction has completed. Thus, if you’re trying to use the sortedfriends data right after you call thefacebookfunction, the data will not be there yet because the login call has not completed yet.The only way to use the
sortedfriendsdata is from the success handler to the login call (where your console.log already verifies that the data is there). If you want to use it in other code, then call that other code from the success handler to the login call. You cannot call that code right after calling thefacebookfunction.This logic will not work because of the asynchronous nature of the login call (it hasn’t completed when the
facebookcall returns and execution continues after it:Instead, you have to do this type of structure:
And, inside your facebook call where you have this, add a function call to whatever code you want to use the sortedfriends data: