开发者

Timing of AJAX calls to Facebook API

So I have some code where I grab the logged in users Facebook ID through their API. That looks like this:

var facebookId = "";
facebookId = getFBIdSafe();

The method call to get it looks like this:

function getFBIdSafe()
{
    FB.api('/me', function(response) {
        if (!response || response.error) {
            return "";
        } else {
            return response.id;
        }
    });
}

What's happening is, I call this method as I showed above, and then go and do other stuff, one of those things being an AJAX call to my own server passing in the facebookId that was "set". Problem is, it's never set.

I'd prefer not to put the FB.api calls all over the place in my code just so I can put my other code in the success call back of it. How can I cleanly take care of this and make sure that this Id always comes back before I make the call to my own server?

P.S. It doesn't execute this code unless the user is logged in to Facebook in the first place - that check happens bas开发者_如何学编程ed on a status marker on the site though - so it's not the same issue.


If what you want is avoid retrieving the current user's FB Id, then you should delay all your server calls until the id is obtained. If you have jQuery or are willing to use jQuery, you can use a $.Deferred() to defer all your server calls until the FB Id is retrieved. I'm suggesting to do something lke this:

var FBIdLoad = $.Deferred();
function getFBIdSafe()
{
    FB.api('/me', function(response) {
        if (!response || response.error) {
            FBIdLoad.resolveWith("");
        } else {
            FBIdLoad.resolveWith(response.id);
        }
    });
}

[...]

FBIdLoad.done(function(FBId){
  /* Your server call with the Id */
}

All functions passed to the FBIdLoad.done will automatically be executed if the object was already resolved (when the FB.Api responds with the id), and always receive the requested Id.

Hope it helps,

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜