递归异步函数,内部保存猫鼬



我在尝试构建一个相当复杂的函数时遇到了问题。它是异步和递归的,基于节点树在Mongoose数据库中创建它们的实例。

我发送的样本数据可以是这样的:

parent1{[name:"Name1", children:[{name:Name2, children[{name:Name4, children:[]}]}, {name: Name3, children:[]}]

因此,理想情况下,它是获取Name1的子级(Name2和Name3(,然后遍历它们,首先到达Name2,然后递归到其子级,因此从Name4作为第一个,然后是Name2,再到Name3,因为它没有子级,所以保存它。我试图让代码在创建项时停止(ergo:Name3是在创建Name4之后才在数据库中创建的,而Name3是最终创建的(。我正在使用以下代码,基于我迄今为止在stackoverflow上发现的内容:

async function recurrentlyCreateChildren(childrenArray){
if(childrenArray.length>0){
await childrenArray.reduce(async(child) => {
if(child.children.length>0){
recurrentlyCreateChildren(child.children);
tempDic=  new Node({
name: child.name,
children: [],
});
await tempDic.save(function(err, dicSystem) {
if (err) {
console.log("Success");
}else{
console.log("SAVED");
}
});
}else{
tempDic=  new Node({
name: child.name,
children: [],
});
await tempDic.save(function(err, dicSystem) {
if (err) {
console.log("SHOW US ERROR", err);
}else{
console.log("SAVED");
}
});
}
});
return;
}else{
return;
}
}

然而,节点是完全随机形成的(而且,它不会到达Name3,只是创建Name2(。如何更改它以使其按预期运行?

一些需要更改的内容:

  • 不要使用reduce(在没有正确使用累加器的情况下(,而是使用纯循环
  • 不要向save方法传递回调以使其返回promise
  • 实际上await也是递归调用
  • 消除不必要的条件
async function createChildren(childrenArray) {
for (const child of childrenArray) {
await recurrentlyCreateChildren(child.children);
const tempDic = new Node({
name: child.name,
children: [],
});
await tempDic.save();
console.log("Saved", child.name);
}
console.log("Saved all "+childrenArray.length+" children");
}

最新更新