1

我正在尝试使用 Facebook JavaScript API 计算朋友的性别。问题是 FB SDK 基于异步调用,所以在完成所有查询后我无法触发操作。

例如,这是计算我有多少男性/女性朋友的代码。但是最后一行不起作用,因为它可以在 FB.api() 仍在运行时执行。

处理这个问题的最佳方法是什么?

FB.api('/me/friends', function(response) {
    if(response.data) {
        var genderCount = {};

        $.each(response.data, function(index, friend) {
            FB.api('/' + friend.id, function(frienddata) {
                if (frienddata.gender) {
                    if (genderCount[frienddata.gender]) {
                        genderCount[frienddata.gender]++;
                    }
                    else {
                        genderCount[frienddata.gender]=1;
                    }
                }
            });
        });
});

// later do something with genderCount

alert('I have ' + genderCount['male'] + ' male friends'); // won't work
4

2 回答 2

0
FB.api('/me/friends', function(response)
{
if(response.data) 
{
    var genderCount = {};
    var i = 0;
    function GetGender(friend_id)
    {
        FB.api('/' + friend_id, function(frienddata) 
        {
            if (frienddata.gender) 
            {
                if (genderCount[frienddata.gender]) 
                {
                    genderCount[frienddata.gender]++;
                }
                else 
                {
                    genderCount[frienddata.gender]=1;
                }
            }

            if(i == response.data.length - 1)
            {
                Results(genderCount);
            }
            else
            {
                GetGender(response.data[++i].id);
            }
        });
    }

    GetGender(response.data[i].id);
}
});


function Results(genderCount)
{
// here you are after all the calls
}
于 2012-12-09T01:14:14.103 回答
0

首先,您可能希望使用更高效的fql查询,例如

SELECT name, sex, uid 
FROM user 
WHERE uid in (
  SELECT uid2 
  FROM friend 
  WHERE uid1 = me()
)

只需将其传递给graph.facebook.com/fql?q=SELECT%20%name....

然后,在完成对数字求和后,将警报移动到响应处理程序中。

FB.api('/fql', 
  {q: "SELECT name, sex, uid FROM user WHERE uid in (SELECT uid2 FROM friend WHERE uid1 = me())"}, 
  function (response) {
    if (response.data) {
        var genderCount = {
            male: 0,
            female: 0,
            unknown: 0
        };
        response.data.forEach(function (row) {
            genderCount[row.sex || 'unknown']++;
        });
        alert(JSON.stringify(genderCount));
    }
});
于 2012-12-09T04:01:49.807 回答