Ben Pearce
Ben Pearce

Reputation: 7094

FB.api pagination without nesting

I'm trying to generate a users entire friend list via Facebook's javascript API. I am able to get 50 (or so) of the users friends using the following call.

FB.api("me/friends",function(response){
//Do something with response
});

I know if the user has more friends I can get 50 (or so) more with the following code:

FB.api("me/friends",function(response){
    if (response.paging.next != "undefined"){
        FB.api(response.paging.next,function(response){
        }
     }
});

This however is not ideal because in order to get an indeterminately long friend list I just need to nest a whole bunch of FB.api functions and hope I have enough. Can anyone suggest another way?

Upvotes: 3

Views: 3062

Answers (1)

Donatas
Donatas

Reputation: 171

Try using recursion:

FB.api("me/friends", doSomething);

function doSomething(response){
   if (response.paging.next != "undefined"){
       FB.api(response.paging.next, doSomething);
   }
}

Hope this helps!

Upvotes: 12

Related Questions