【问题标题】:How to recurse asynchronously over API callbacks in node.js?如何通过 node.js 中的 API 回调异步递归?
【发布时间】:2013-06-19 00:27:48
【问题描述】:

API 调用返回下一个“页面”结果。如何优雅地递归该结果回调?

这是我需要这样做的示例:

var url = 'https://graph.facebook.com/me/?fields=posts&since=' + moment(postFromDate).format('YYYY-MM-DD') + '&access_token=' + User.accessToken;
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
            //?????????
        }
    } else {
        console.log(error);
        throw error;
    }

});

【问题讨论】:

    标签: javascript node.js asynchronous


    【解决方案1】:

    我建议将调用包装在一个函数中,并在必要时继续调用它。

    我还会添加一个回调以了解该过程何时完成。

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

    【讨论】:

    • 完美 - 谢谢。现在太明显了。顺便说一句 - 在这种情况下,我是否有理由使用函数 getFacebookData() 与 var getFacebookData=function()?
    • 没有硬的理由只有软的那些是 - 首先它至少对我来说是一种更自然的定义函数的方式,其次如果你忘记了“var”,那么它就会变成一个全局函数。第三个也是最有用的——如果以这种方式声明,函数将有一个名称而不是匿名的。这有它的用途。其中最简单的是 - 它会显示在堆栈跟踪中。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-12-18
    • 1970-01-01
    • 2017-10-28
    • 1970-01-01
    • 1970-01-01
    • 2018-01-30
    • 1970-01-01
    相关资源
    最近更新 更多