0

我有这样的代码:返回查询结果使用自定义功能

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

回答

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); 
+0

开箱即用! Ur一个js忍者! tnx – zsitro 2012-02-01 13:14:15

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"]); 
    }); 


}; 
+0

感谢大概这个答案是一样的第二个。它帮助了我! – zsitro 2012-02-01 13:15:13