9

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:

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

});
metalaureate
  • 7,572
  • 9
  • 54
  • 93

1 Answers1

19

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');
});
Matthew Lock
  • 13,144
  • 12
  • 92
  • 130
DeadAlready
  • 2,988
  • 19
  • 18
  • Perfect - thank you. So obvious now. Incidentally - is there a reason I would use function getFacebookData() vs. var getFacebookData=function() in this case? – metalaureate Jun 23 '13 at 16:28
  • 1
    No hard reason only soft ones and those are - Firstly it is at least for me a more natural way of defining a function, secondly if you were to forget the "var", then it would become a global function. And third and most useful - if declared the this way the function will have a name instead of being anonymous. This has it's uses. And the simplest of them being - it'll show up in the stack trace. – DeadAlready Jun 24 '13 at 15:27