Asynchronous Method In While Loop With Graph Api Paged
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 returne
Solution 1:
My idea of solving this with async/await:
asyncfunctiongetFeed(token) {
let feedItems = [],
hasNext = true,
apiCall = '/me/feed';
while (hasNext) {
awaitnewPromise(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);
});
Be aware that you need Node.js 7.9.0+ for this: http://node.green/
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.
Solution 2:
Instead of using:
feedItems.concat(response.data);
I have made: (if is the case on response.data has the data)
for(vari in response.data){
feedItems.push(response.data[i]);
}
Solution 3:
As of today (12/10/21) response.data is of type Object. The below would now be appropriate for saving response data.
for (let d of response.data) {
feedItems.push(d)
}
Post a Comment for "Asynchronous Method In While Loop With Graph Api Paged"