Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Asynchronous tree traversal using async.js

I'm trying to traverse a tree of nested of items using async.js. The traversal terminates after going through just 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;
            }
        }
    });
};
like image 433
Kinnard Hockenhull Avatar asked Oct 09 '15 02:10

Kinnard Hockenhull


1 Answers

The logic is quite a bit convoluted so I'd make sure that's fine first. Here's a few things that you probably missed. count += like previously mentioned. No callback inside your iterator and you were also pushing family inside extendedFamily.kids twice.

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();
        }
    })
})
like image 81
Rahat Mahbub Avatar answered Oct 05 '22 11:10

Rahat Mahbub