Problema de bucle de consultas de Facebook

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.

preguntado el 09 de marzo de 12 a las 15:03

3 Respuestas

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.

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

respondido 09 mar '12, 15:03

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 dentro the response function, like right after that for loop, things should work better.

respondido 09 mar '12, 15:03

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 lanzado cuando usted llama FB.api(), pero no lo es terminado 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 algún tiempo después.

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 algún tiempo después, it's length is 0; and you're trying to access the 2nd element.

respondido 09 mar '12, 15:03

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.