Asynchronous tree traversal using async.js

I am trying to traverse a tree of nested elements using async.js. A crawl ends after passing only one branch.

var count=0; exports.buildFamily = function(item_id, mback){ var extendedFamily={}; exports.getItembyId(item_id, function(err, item){ extendedFamily=item; if(item.descendants){ extendedFamily.kids=[]; count=+item.descendants.length; console.log('outercount ' + count); async.eachSeries(item.descendants, function(item){ count-- console.log('item: ' + item) exports.buildFamily(item, function(err, family){ console.log('deepcount: ' + count); extendedFamily.kids.push(family); if(count===0){ return mback(null, extendedFamily);} else {extendedFamily.kids.push(family);} }) }) } else{ if(count===0){ return mback(null, extendedFamily);} else{ extendedFamily.kids.push(family); return; } } }); }; 
+7
recursion nested tree
source share
2 answers

I misunderstood the use of callback() in the async.js library. This article helped me understand: http://www.sebastianseilund.com/nodejs-async-in-practice This was my solution:

 exports.buildFamily = function(item_id, done){ console.log('API:buildFamily'); var extendedFamily={} exports.getItembyId(item_id, function(err, item){ if(err){throw err} extendedFamily=item; if(item.descendants){ extendedFamily.kids=[] async.eachSeries(item.descendants, function(item_id, callback){ exports.getItembyId(item_id, function(err, item){ if(err){throw err} if(item.descendants){ exports.buildFamily(item.item_id, function(err, family){ extendedFamily.kids.push(family); callback(); }) }else{ extendedFamily.kids.push(item); callback(); } }) }, function(err){ done(null, extendedFamily) }) }else{ done(null, extendedFamily) } }); } 
0
source share

The logic is pretty confusing, so I have to make sure of this first. Here are a few things you probably missed. count += as already mentioned. There is no callback inside your iterator, and you also double clicked the family inside extendedFamily.kids.

 count += item.descendants.length; console.log('outercount ' + count); async.eachSeries(item.descendants, function(item, cb) { count--; console.log('item: ' + item); exports.buildFamily(item, function(err, family){ console.log('deepcount: ' + count); if(count===0){ return mback(null, extendedFamily);} else { extendedFamily.kids.push(family); cb(); } }) }) 
+2
source share

All Articles