图API的While循环中的异步方法分页 [英] Asynchronous method in while loop with Graph API paged
问题描述
我正在使用 facebook节点sdk 来获取node.js.来自Facebook用户的信息(例如其供稿和朋友),效果很好.
I'm using facebook node sdk for node.js to get information from a facebook user such as their feed and friends, which is working fine.
但是,在返回的数据被分页时,我遇到了问题-我需要以递归模式构建某些内容.让我解释一下:
However I'm having an issue where the returned data is paged - I need to build something in recursive mode. Let me explain:
FB.api('/me/feed?limit=5000', {
access_token: token
}, function(response) {
// response is an object that could have as response.paging.next attribute
});
限制在这里不起作用,因为它最多返回245,并返回指示下一页结果的 paging 对象.
Limit isn't working here, because it returns a max of 245 and returns paging object indicating the next page of results.
由于下一个调用取决于上一个异步调用的结果,因此我尝试执行以下操作:
Because the next call depends of the result of the previous async call, I tried to do something like this:
// first call before
var hasNext = response.paging.next ? true : false;
while (hasNext){
FB.api('/me/feed', {
access_token: token
}, function(response_paged) {
response.data.concat(response_paged.data);
// If do not have a next page to break the loop
if (!response_paged.paging.next) hasNext = false;
});
}
获取下一个令牌的方式目前并不重要
关键是我试图以递归模式进行异步调用,但是它不起作用,这样我就遇到了无限循环.
The point is I'm trying to do async calls in recursive mode, but its not working, this way I'm getting an infinite loop.
推荐答案
我用async/await解决此问题的想法:
My idea of solving this with async/await:
async function getFeed(token) {
let feedItems = [],
hasNext = true,
apiCall = '/me/feed';
while (hasNext) {
await new Promise(resolve => {
FB.api(apiCall, {access_token: token}, (response) => {
feedItems.concat(response.data);
if (!response.paging.next) {
hasNext = false;
} else {
apiCall = response.paging.next;
}
resolve();
});
});
}
return feedItems;
}
getFeed().then((response) => {
console.log(response);
});
请注意,您需要为此使用Node.js 7.9.0+: http://node.green/
Be aware that you need Node.js 7.9.0+ for this: http://node.green/
对于旧版本,请安装以下版本: https://github.com/yortus/asyncawait
For older versions, install this: https://github.com/yortus/asyncawait
您还可以使用递归函数,但是平滑/现代的方式是异步/等待.
You can also use a recursive function, but the smooth/modern way would be async/await.
这篇关于图API的While循环中的异步方法分页的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!