简体   繁体   中英

How to return a value from a recursive asynchronous callback?

I'm using the facebook js sdk, I'm trying to get a list of all groups, the response is pageinated. So recursion seems like a an obvious solution for this

function handlePaging(response) {
  if (response && !response.error) {
    if (response.paging.next) {
      return response.data.concat(FB.api(response.paging.next, handlePaging));
    } else {
      return response.data;
    }
  }
}

console.log(FB.api("/me/groups", handlePaging));

But because its asynchronous I'm getting undefined returned. I've had a look at other returning values from asynchronous requests, but none of them were recursive, and the answer was use a callback, which I have.

I'm not even sure if this is even possible.

The call to FB.api is asynchronous so it returns immediately usually before the call to the server is made and the handlePaging callback is invoked. Try something like this

    var data = [];

    function handlePaging(response) {

      if (response && !response.error) {

        data = data.concat(response.data);

        if (response.paging.next) {
          FB.api(response.paging.next, handlePaging);
        } else {
          console.log(data);
        }

      }

    }

    FB.api("/me/groups", handlePaging);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM