简体   繁体   中英

Node.js Recursive Reddit API Calls

I'd like to get a list of all users' flairs on a particular subreddit. Reddit splits the requests up into chunks of 1,000 and allows a "before" and "after" parameter so that all of these can be fetched. However, I can't get my head around how to create a recursive function to return an object containing everything.

An example request would be something like:

GET http://www.reddit.com/r/soccer/api/flairlist.json?limit=1000&after=t2_83wp8

The returned response would be a JSON object, with an array of users and a "prev" and "next" string which can be placed into the "before" and "after url parameters respectively.

It's something like this:

function getEverything(callback) {

    var results = [];

    function getSomeMore(callback, after) {
        var url = 'http://...?limit=1000' + (after ? 'after=' + encodeURIComponent(after) : '');
        makeAjaxRequest(url, function(err, body) {
            if (err) return cb(err);
            results = results.concat(body.results);
            if (body.after)
                getSomeMore(callback, body.after);
            else
                callback(null, results);
        });
    }

    makeAjaxRequest(callback);
}

... and use it something like this:

getEverything(function (err, everything) {
    if (err) return console.log('ERROR: cant get everything:', err);
    console.log('everything:', everything);
});

Though this is obviously pseudo-code only.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM