我有这段代码:
getThirdPartyID : function () {
return FB.api("/me?fields=third_party_id", function (userData) {
console.debug("Your Facebook ThirdPartyId is: " + userData["third_party_id"]);
return userData["third_party_id"];
});
},
但它返回空。这个代码有什么问题?我怎样才能以同样的想法访问它? TNX
答案 0 :(得分:4)
FB.api
是对Facebook API进行异步请求并且不返回任何内容的函数。您只能在callback
内获得结果。您应该利用不同的方法来实现这一点:
var someObj = {
getThirdPartyID : function (thirdPartyIDCallback) {
return FB.api("/me?fields=third_party_id", function (userData) {
console.debug("Your Facebook ThirdPartyId is: " + userData["third_party_id"]);
thirdPartyIDCallback(userData["third_party_id"]);
});
}
}
var handleThirdPartyID = function(thirdPartyID){
// do something with thirdPartyID
alert(thirdPartyID);
}
someObj.getThirdPartyID(handleThirdPartyID);
答案 1 :(得分:1)
FB.api工作异步。这意味着函数在FB.api回调函数返回之前返回。
您应该将FB.api的返回值设置为变量或调用FB.api回调函数内的其他函数。
function GetUserData(val){
alert(val);
}
getThirdPartyID : function () {
FB.api("/me?fields=third_party_id", function (userData) {
console.debug("Your Facebook ThirdPartyId is: " + userData["third_party_id"]);
GetUserData(userData["third_party_id"]);
});
};