使用async.js进行异步树遍历 [英] Asynchronous tree traversal using async.js
本文介绍了使用async.js进行异步树遍历的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用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;
}
}
});
};
推荐答案
我误解了async.js
库中callback()
的用法.本文有助于我理解: http://www.sebastianseilund.com/nodejs-async实践中
这是我的解决方案:
I misunderstood the use of the callback()
in the async.js
library. This article helped me get an understanding: 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)
}
});
}
这篇关于使用async.js进行异步树遍历的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文