开发者

Callback code seems to run before callback is actually called

This sounds like a weird title and probably not stated too well. But here's the issue.

I've got this method being called:

function BindFacebookAlbumAndPhotoData() 
{
    GetAllFacebookAlbums(userID, accessToken, function(aAlbums) 
    {
        if (aAlbums === null || aAlbums === undefined) 
        {
            // TODO: Need to handle this
            return;
        }

        var defaultAlbumID = aAlbums[0].id;

        BindFacebookAlbumDropdownList(aAlbums, defaultAlbumID);

        BindFacebookThumbnails(userID, accessToken, defaultAlbumID, photosContainerDivID);

        SetSelectDefaultOption(defaultAlbumID);
    });
}

So here's the GetAllFacebookAlbums Method:

function GetAllFacebookAlbums(userID, accessToken, callbackFunction)
{
    var aAlbums = [];
    var uri = "/" + userID + "/albums?access_token=" + accessToken;

    // this is an async call so code after this will fire at the same time
    FB.api(uri, function(response) 
    {
        // check for a valid response
        if (!response || response.error) 
        {
            callbackFunction(albums);
        }

        for (var i = 0, l = response.data.length; i < l; i++) 
        {
            //do whatever
        }
    });

    // wait for the FB.api call to run a bit before calling code below
    window.setTimeout(callbackFunction(aAlbums), 5000);
}

What's happening is this line is being call开发者_如何转开发ed before the setTimeout it seems:

var defaultAlbumID = aAlbums[0].id;

the whole reason I put that timeout in there is so I can wait for the FB.api call to finish. Then call the callback after I know I have data. So how in the world are those lines in my callback being called when I have definitely not seen a 5 second delay before that callback is called?


This line right here:

window.setTimeout(callbackFunction(aAlbums), 5000);

You're calling the function right there in the setTimeout() call. Wrap it in another function:

window.setTimeout(function() { callbackFunction(aAlbums); }, 5000);

Now, that said, the whole setup doesn't really make much sense. You've already got code sitting in a place that you know will be called as soon as the data is ready. That's the code in the Facebook API callback you've got. Why not just call your "callbackFunction" from in there?


It's my understanding you should do

    [/code` window.setTimeout(callbackFunction, 5000, aAlbums);`]

instead of:

    [/code`window.setTimeout(function() { callbackFunction(aAlbums); }, 5000);`]

I do belive both will work, but the first seems easier to read, write and understand

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜