I want to return the value of a callback function, as shown bellow. Not managing to understand how to make it work (implementation for explaining purposes only)
console.log( hasLogin() );
function hasLogin(){
FB.getLoginStatus(function(r开发者_Python百科esponse) {
if (response.session) {
return true;
}
else {
return false;
}
});
}
In practice, I want hasLogin() to return true is response.session exists/is true.
Thanks!
You don't - since getLoginStatus
is designed to be asynchronous, the result is simply not available yet. The best strategy is to stay asynchronous:
function checkLogin(result_callback) {
FB.getLoginStatus(function(response) {
result_callback(!!response.session);
}
}
check_login(function(result) {console.log(result);});
That's how it is usually done in JavaScript. Of course it forces you to rethink your code flow.
getLoginStatus
is calling your anonymous function, and that function is returning true or false, not hasLogin
. hasLogin is actually returning undefined
. Since this is happening asynchronously, you'll need to do something like this:
FB.getLoginStatus(function(response) {
console.log(response.session);
});
Asynchronous calls can be tricky to deal with.
You can't really do this, because getLoginStatus
runs asynchronously that's why it provides callback function.
What you can do is:
function hasLogin(){
FB.getLoginStatus(function(response) {
if (response.session) {
console.log("got session");
}
else {
console.log("got no session");
}
});
}
精彩评论