0

我打电话给 facebook fql 来获取一个组的所有成员。如果我在第一个函数中检查所有成员,它工作得很好,但是当我在第二个函数中调用它时,返回“未定义”。

function getAllMembers(groupid){
              var allmembers = new Array();
              var content = document.getElementById('content-text');
              FB.api({
                method: 'fql.query',
                query: 'select uid from group_member where gid =' + groupid
              },
              function(resp){
                for (var i=0, l= resp.length; i<l; i++)
                {
                 allmembers[i] = resp[i].uid;
                }
                return allmembers;
              }
              )    
    }

    function retrieveMessages(groupid){
        var allmembers;
        allmembers = getAllMembers(groupid);
        console.log(allmembers);     
    }

I don't understand where's the mistake.

4

2 回答 2

2

貌似getAllMembers()是在使用FBAPI​​进行异步函数调用,也就是说getAllMembers()FB调用完成前的返回。

您需要使用回调函数来解决这个问题,如下所示

function getAllMembers(groupid, callback){
    var content = document.getElementById('content-text');
    FB.api({
        method: 'fql.query',
        query: 'select uid from group_member where gid =' + groupid
    },  function(resp){
        var allmembers = new Array();
        for (var i=0, l= resp.length; i<l; i++)
        {
            allmembers.push( resp[i].uid);
        }
        callback(allmembers)
    })    
}

function retrieveMessages(groupid){
    getAllMembers(groupid, function(allmembers){
        console.log(allmembers);     
    });
}
于 2013-04-27T11:02:40.477 回答
0

猜测调用是异步的 - 这意味着getAllMembers在您的成功函数(function(resp){})执行之前返回......

尝试移动console.log您的内部function(resp)...

var allmembers = new Array();

function getAllMembers(groupid){
          var allmembers = new Array();
          var content = document.getElementById('content-text');
          FB.api({
            method: 'fql.query',
            query: 'select uid from group_member where gid =' + groupid
          },
          function(resp){
            for (var i=0, l= resp.length; i<l; i++)
            {
             allmembers[i] = resp[i].uid;
            }
            console.log(allmembers);     
          }
          );    
}

function retrieveMessages(groupid){
    getAllMembers(groupid);
}
于 2013-04-27T11:01:54.720 回答