Asynchronous method in while loop with Graph API paged

后端 未结 2 953

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 wher

相关标签:
2条回答
  • 2021-01-25 04:23

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

    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.

    0 讨论(0)
  • 2021-01-25 04:25

    Instead of using:

    feedItems.concat(response.data);
    

    I have made: (if is the case on response.data has the data)

    for(var i in response.data){
       feedItems.push(response.data[i]);
    }
    
    0 讨论(0)
提交回复
热议问题