Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.