Skip to content

Instantly share code, notes, and snippets.

@notajingoist
Last active December 20, 2015 21:18
Show Gist options
  • Save notajingoist/6196721 to your computer and use it in GitHub Desktop.
Save notajingoist/6196721 to your computer and use it in GitHub Desktop.
Recursion + Promises by the brilliant @nhunzaker
function harvest(id, parent) {
var promise = $.Deferred();
var post;
request({
url: "...",
json: true,
timeout: 30000
}, function(error, response, body) {
if (error) return console.log("CRAP");
// Enter the pseudocode....
post = JSON.parse(body);
post.children = [];
// Now assign this post to a parent if it was specified
if (parent) {
parent.children.push(post);
}
// Now for each reblog (or whatever it's called) do it again,
// which will assign a parent id, but also this will return
// a promise that we'll use to determine if children are finished
var promises = posts.reblogs.map(function(reply) {
// Go out and get the reply, which will assign the
// post's id as the parent attribute
return harvest(reply, post);
});
$.when.apply($, promises).then(function() {
promise.resolve(post);
});
});
return promise;
}
var posts;
harvest("your seed id").done(function(data) {
posts = data;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment