samn
samn

Reputation: 2807

Facebook query looping issue

I have the following JavaScript code which gets all of the id's of the albums of the user who's currently logged in:

function fqlQuery(){
            showLoader(true);
            var albums= new Array();
            FB.api('/me', function(response) {
                var query =  FB.Data.query('SELECT aid, owner, name, object_id FROM album WHERE owner={0}', response.id);
                var aantal_albums=0;        
                var photos= new Array();
                query.wait(function(rows) {
                aantal_albums= rows.length;     
                    for(var i=0; i<aantal_albums;i++){

                     albums[i]= rows[i].aid;
                    }
                 });
            });
            alert(albums[1]);       
        }

My issue is, the last line, the alert is not working. It is called outside of the function in which the array is filled, but that should be fine, because the array is declared at the top (var albums= new Array), right? I feel like there's an elephant in the room and I can't see it. Do you see anything wrong? I don't know if this is a fql problem or JavaScript.

Upvotes: 1

Views: 142

Answers (3)

jches
jches

Reputation: 4527

You're not thinking asyncronously; the array is not going to be populated until the callback you passed to FB.api runs, and your alert executes before that.

Place the alert inside of your callback function and you should get the results you expect.

Upvotes: 1

Matt
Matt

Reputation: 75317

This is a JavaScript problem. Specifically, it's a problem with your understanding of asynchronous events and callbacks.

If you look at your program structure, it's clear you're:

  1. var albums= new Array(); // creating an Array
  2. FB.api('/me', function() {}); // launching an API request
  3. alert(albums[1]); // accessing the second album

However, what isn't always clear is that the API request is asynchronous. The API request is launched when you call FB.api(), but it isn't completed immediately. This is what the second parameter of FB.api() is for; it allows you to specify a function (i.e. a block of code), whose execution is delayed until the API request has completed some time later.

You can only use the results of your API call in the callback function. Sure, the albums array has been declared; but until it is populated by the callback some time later, it's length is 0; and you're trying to access the 2nd element.

Upvotes: 1

Pointy
Pointy

Reputation: 413720

The API is asynchronous. You won't be able to see the results until the results are actually available.

If you move your alert to inside the response function, like right after that for loop, things should work better.

Upvotes: 1

Related Questions