Asynchronous method in while loop with Graph API paged

后端 未结 2 955

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.

提交回复
热议问题