我正在尝试创建一个回调函数嵌套在回调函数中的家谱,我希望至少有 5 代。该函数接收此人的 id,然后在数据库中查找具有相同 id 属性“父亲”的每个人。
<小时/>这是获取该人的 child 的函数
var getChildren=function (person, callback) {
keystone.list('Person').model.find().where('father', person.id).exec(function(err, children) {
callback(children);
})
}
这就是我使用回调函数的方式
function getFamilyTree(person){
getChildren(person, function(children){
person.children=children;
for (var i=0;i<person.children.length;i++) {
!function outer(i){
if (isNotEmpty(person.children[i])){
getChildren(person.children[i],function(children){
person.children[i].children=children;
for (var j=0;j<person.children[i].children.length;j++){
!function outer(j){
if (isNotEmpty(person.children[i].children[j])){
getChildren(person.children[i].children[j],function(children){
person.children[i].children[j].children=children;
for (var k=0;k<person.children[i].children[j].children.length;k++){
!function outer(k){
if (isNotEmpty(person.children[i].children[j].children[k])){
getChildren(person.children[i].children[j].children[k],function(children){
person.children[i].children[j].children[k].children=children;
})
}
}(k);
}
})
}
}(j);
}
});
}
}(i);
}
})
}
正如你所看到的,它非常复杂。它可以工作,但有时它不能检索所有 5 代,而只能检索 4 或 3 代,有时甚至是 1 代,我不知道为什么,请帮助我的人,我也是一个新来者,所以请对我轻松一点,提前致谢!
最佳答案
如果您使用promises您可以使用递归 async
function 而不是回调解析任意深度的树:
function getChildren(person) {
return new Promise((resolve, reject) => {
keystone.list('Person').model.find().where('father', person.id).exec((err, children) => {
if(err) reject(err);
else resolve(children);
});
});
}
async function getFamilyTree(person, maxDepth, depth=0) {
if(depth >= maxDepth) return person;
const children = (await getChildren(person)).filter(isNotEmpty);
person.children = await Promise.all(
children.map(child => getFamilyTree(child, maxDepth, depth + 1))
);
return person;
}
getFamilyTree({id: 'rootPersonId'}, 5)
.then(tree => console.log(tree))
.catch(error => console.log(error));
关于javascript - 递归回调创建家谱,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50415498/