This is partially a javascript technique question. I am trying to build an object with facebook id as the key, and an array of likes as the value. My issue is the in my innermost function, I cannot access the variable fbid that I need for setting the key.
How to get access to fbid in the scope of the inner anonymous function?
friendsLikes = [];
FB.api('/me/friends',function(friends){
for(var i=0;i<friends.data.length;i++){
var fbid = friends.data[i].id
FB.api(fbid+'/likes',function(likes){
if(likes.data.length>=1){
//this is where I build the object
//I cannot use fbid for the key :(
console.log(likes.data.length);
}
})
}
})
The problem is that
fbidis updated on each iteration, before your callback executes.fbidto the friend’s IDfbidis the same for all callbacks – specifically, it is set to the ID of the last friend in the list.Here’s how I’d capture the
fbidof each iteration:Notice that we use a self-executing function and pass the current
fbid. This returns a function that will have the properfbidin scope.And now a note on how you’re doing this: this code’s performance is going to suck because you’re paying for a HTTP roundtrip for each friend. Remember that a browser will only open somewhere between 2-8 connections per host (depending on browser), and all of these calls are going to graph.facebook.com.
With a modest friend list of 200 and a generous roundtrip time of 150ms, the theoretical best case scenario is ~4 seconds. Things quickly go downhill if the browser will only do 2 concurrent connections and we have a 200ms roundtrip time: 20 seconds.
It’s also highly likely Facebook might rate-limit you at some point.
Instead, you need to use the Batch API.