Facebook JavaScript SDK:在返回所有查询后运行

时间:2012-12-09 00:50:52

标签: facebook-javascript-sdk

我正在尝试使用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

2 个答案:

答案 0 :(得分: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
}

答案 1 :(得分: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));
    }
});