How to recurse asynchronously over API callbacks in node.js?

后端 未结 1 1429
孤城傲影
孤城傲影 2021-01-31 23:40

An API call returns the next \'page\' of results. How do I recurse over that result callback elegantly?

Here is an example of where I need to do this:

va         


        
1条回答
  •  抹茶落季
    2021-02-01 00:06

    I would suggest wrapping the call in a function and just keep calling it until necessary.

    I would also add a callback to know when the process has finished.

    function getFacebookData(url, callback) {
    
        request.get({
            url: url,
            json: true
        }, function (error, response, body) {
            if (!error && response.statusCode == 200) {
                _.each(body.posts.data, function (post) {
                    User.posts.push(post); //push some result
                });
                if (body.pagination.next) { // if set, this is the next URL to query
                    getFacebookData(body.pagination.next, callback);
                } else {
                    callback(); //Call when we are finished
                }
            } else {
                console.log(error);
                throw error;
            }
    
        });
    }
    
    var url = 'https://graph.facebook.com/me/?fields=posts&since=' + 
        moment(postFromDate).format('YYYY-MM-DD') + '&access_token=' + User.accessToken;
    
    getFacebookData(url, function () {
        console.log('We are done');
    });
    

    0 讨论(0)
提交回复
热议问题