FB.api pagination without nesting

2019-04-12 07:22发布

问题:

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?

回答1:

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!