The issue I am having is that I need to get a total count of a collection of objects, which has the form of a tree where each object can also contain deeply nested objects. The collection of data I start with already has one nested layer available, but to find out if there is a third or more nested layers in an object, an API call has to be made with the nested object's id, which returns the next nested object if it exists. So, currently I have something like this:
function getCount(thread) {
var deferred = $q.defer();
var count = 0;
function getComment(comment) {
count++;
//if nested comments exist in data
if (comment.fld.nested) {
_.each(comment.fld.nested, function(x) {
getComment(x);
});
deferred.resolve(count);
} else if (comment.meta) {
//if not, load more from API with id
return PostService.getComment(comment.meta.id).then(function(comment){
if (comment.fld.nested) {
_.each(comment.fld.nested, function(x) {
return getComment(x);
});
}
return count;
});
}
return deferred.promise;
}
_.each(thread.fld.nested, function(x) {
return getComment(x);
});
return deferred.promise;
}
getCount(c).then(function(x) {
console.log('final count:', x);
});
Right now, I can get the count for all objects nested to 2nd level deep, but anything loaded from the API promise is not included in the count when I call the getCount().then() function. How do I make this wait until all promises are resolved so I can get the final count returned?