如何使用承诺和递归通过Facebook Graph API检索用户的所有帖子? [英] How to retrieve all posts of a user via Facebook Graph API using promises and recursion?
问题描述
我目前正在开发一个使用Facebook Graph API的网络应用。
I am currently developing a web app which uses the Facebook Graph API.
我想要实现的是获取用户的所有帖子。
What I would like to achieve is to get all posts of a user.
但是,这并不是一件容易的事,因为我必须对结果进行分页。
However, this is not that easy since I have to paginate the results.
此刻,我在兑现诺言
我试图实现的是用post对象填充数组。
What I try to achieve is to fill an array with the post objects.
因此,我使用promises
Therefore I use promises and recursion which does not work as expected.
我的代码当前如下所示:
My code currently looks as follows:
// Here I retrieve the user with his or her posts,
// just the first 25 due to pagination
if (accessToken) {
return new Promise(resolve => {
FB.api('/me?fields=id,name,posts&access_token=' + accessToken, response => {
this.get('currentUser').set('content', response);
resolve()
})
})
}
// Returns all posts of a given user
function getAllPostsOfUser(posts, postsArr) {
// Process each post of the current pagination level
for (var post of posts.data) {
// Only store meaningful posts
if (post !== undefined && post.message !== undefined) {
postsArr.push(post)
}
}
// Further posts are retrievalable via paging.next which is an url
if (posts.data.length !== 0 && posts.paging.next !== undefined) {
FB.api(posts.paging.next, response => {
getAllPostsOfUser(response, postsArr)
resolve()
})
}
return postsArr
}
var posts = getAllPostsOfUser(this.get('currentUser').content.posts, [])
// I want to use all the posts here
console.log(posts)
我的问题是我想使用放置console.log的帖子,但是当我记录这些帖子时阵列中缺少很多帖子。
The problem I have is that I want to use the posts where the console.log is placed but when I log the posts array a lot of posts are missing.
我确定我对诺言的确做错了,但我不知道是什么。
I am sure that I did something wrong with the promises but I do not know what.
如果有人可以指导我找到解决方案,我将感到非常高兴。
I would be glad if anyone could guide me to a solution.
谢谢您。
推荐答案
尝试以下操作:
function getAllPosts() {
return new Promise((resolve, reject) => {
let postsArr = [];
function recursiveAPICall(apiURL) {
FB.api(apiURL, response => {
if (response && response.data) {
//add response to posts array (merge arrays), check if there is more data via paging
postsArr = postsArr.concat(response.data);
if (response.paging && response.paging.next) {
recursiveAPICall(response.paging.next);
} else {
resolve(postsArr);
}
} else {
reject();
}
})
}
recursiveAPICall('/me/posts?fields=message&limit=100');
}
}
getAllPosts().then(response => {
console.log(response);
}).catch(e => {
console.log(e);
});
未经测试,只是我想出的一个简单例子。它返回一个Promise,并使用递归函数获取所有条目。顺便说一句,您不需要添加访问令牌。如果您已登录,则SDK将在内部使用它。
Not tested, just a quick example i came up with. It returns a promise and uses a recursive function to get all entries. Btw, you don´t need to add the Access Token. If you are logged in, the SDK will use it internally.
这篇关于如何使用承诺和递归通过Facebook Graph API检索用户的所有帖子?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!