使用 async.js 的异步树遍历

Asynchronous tree traversal using async.js

我正在尝试使用 async.js 遍历嵌套项的树。遍历仅通过一个分支后终止。

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;
            }
        }
    });
};

逻辑有点复杂,所以我先确定一下没问题。以下是您可能错过的几件事。 count += 如前所述。在你的迭代器中没有回调,你也在 extendedFamily.kids 中推了 family 两次。

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();
        }
    })
})

我误解了 async.js 库中 callback() 的用法。这篇文章帮助我理解了:http://www.sebastianseilund.com/nodejs-async-in-practice 这是我的解决方案:

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)
        }
    });
}