繁体   English   中英

如何从递归异步回调返回值?

[英]How to return a value from a recursive asynchronous callback?

我正在使用facebook js sdk,正在尝试获取所有组的列表,响应是分页的。 因此,递归似乎是一个明显的解决方案

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));

但是因为它是异步的,所以我得到的是不确定的返回。 我看过异步请求中的其他返回值,但是它们都不是递归的,答案是使用回调函数。

我什至不确定这是否可能。

FB.api的调用是异步的,因此通常在对服务器的调用和handlePaging回调被调用之前立即返回。 试试这个

    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);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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