简体   繁体   中英

Getting the number of mutual friends using Facebook Graph API

So I use the code below to get the users friends first, and then use the users friends IDs to generate the number of mutual friends that they have. Clearly iterating through all the friends and comparing it each time is a lengthy process but it works. However, the page takes a while to load. How do I reduce the time it takes or optimize the following code?

    function getFriends() 

    {
      FB.api('/me/friends', function(response) {
      friendCount = response.data.length;
      $("h2").append(friendCount+ ' friends');
      if(response.data) {
        $.each(response.data,function(index,friend) {
            FB.api('/me/mutualfriends/'+friend.id, function(mutualfriends) {
            $("#results").append('<ul><li>' + friend.name + ' has id:' + friend.id + ' has mutual friends: ' + mutualfriends.data.length + '</li></ul>');
            $("#results").append('<img src="http://graph.facebook.com/' + friend.id + '/picture" />');
            });

        });
    } else {
        console.log("Error!");
    }
    });
    }

I know this is a really old question but I am still adding this answer for somebody who may end up looking here.
This is a an optimized way to get count of mutual friends using FQL.

select mutual_friend_count,uid,name from user where uid in 
(select uid2 from friend where uid1=me()) order by mutual_friend_count desc

You should use Facebook Batch Api. With it you can enqueue more requests into one, and pay the latency cost only once. https://developers.facebook.com/docs/reference/api/batch/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM