如何通过node.js中的API回调异步递归?

时间:2013-06-21 19:07:41

标签: javascript node.js asynchronous

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

});

1 个答案:

答案 0 :(得分:17)

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

我还会添加一个回调来知道进程何时完成。

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