使用async.js进行异步树遍历

时间:2015-10-09 02:57:00

标签: node.js recursion tree nested async.js

我试图使用async.js遍历嵌套项目的树。经过一个分支后,遍历终止。

 if (dt.Columns[i].ColumnName == "Employee Number")
            {
                textBoxTable.Size = new SizeU(Unit.Inch(.5), Unit.Inch(0.3));
            }
            if (dt.Columns[i].ColumnName == "Employee Name")
            {
                textboxGroup.Size = new SizeU(Unit.Inch(2.1), Unit.Inch(0.3));
            }
            else
            {
                textBoxTable.Size = new SizeU(Unit.Inch(.90), Unit.Inch(0.3));
            }
            if (dt.Columns[i].ColumnName.ToLower().Contains("share"))
            {
                textBoxTable.Style.Color = Color.Chocolate;
                textboxGroup.Size = new SizeU(Unit.Inch(0.9), Unit.Inch(0.3));
            }

2 个答案:

答案 0 :(得分:2)

这个逻辑有点令人费解,所以我确保先做好。这里有一些你可能错过的东西。像先前提到的那样计算+=。你的迭代器中没有回调,你也在expandFamily.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();
        }
    })
})

答案 1 :(得分:0)

我误解了callback()库中async.js的使用。这篇文章帮助我理解: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)
        }
    });
}