用javascript sdk获取facebook用户ID。并使用全球?

时间:2012-03-04 23:00:52

标签: javascript facebook

我想在其他功能中使用用户的脸书ID。我使用了返回,但它没有用。我的代码有什么问题?

function get_id(){
    FB.login(function(response) { 
            if (response.authResponse) {
                var token = response.authResponse.accessToken;
                FB.api('/me?access_token='+token+'', function(response) {
                    var id = response.id;
                    return id;
                });
            }
    });
    }
    var user_id = get_id();

这是一个Facebook应用程序。并且,我使用了多个朋友选择器的代码,但我想使用用户ID全局。

1 个答案:

答案 0 :(得分:2)

您无法从异步函数返回结果。让你的函数接受回调而继续在那里。

function get_id(cb) {
    FB.login(function (response) {
        if (response.authResponse) {
            var token = response.authResponse.accessToken;
            FB.api('/me?access_token=' + token + '', function (response) {
                cb(response.id);
            });
        }
    });
}

get_id(function (user_id) {
    console.log(user_id);
});