【问题标题】:Recursive asynchronouse function with mongoose saving inside内部带有猫鼬保存的递归异步函数
【发布时间】:2021-03-20 22:05:27
【问题描述】:

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

我发送的示例数据如下所示:

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

所以理想情况下,它是让 Name1 的孩子(Name2 和 Name3)然后遍历它们,首先到达 Name2 并递归到它的孩子,因此首先从 Name4 开始,然后是 Name2,然后转到 Name3,因为它有没有孩子,保存它。我试图在创建项目时停止代码(ergo:仅在创建 Name4 之后在数据库中创建 Name3,最后创建 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)。如何更改它以使其按预期执行?

【问题讨论】:

  • 您不能将await 与回调一起使用……它不能那样工作。你await的函数需要返回一个promise。
  • 您对reduce 的使用毫无意义,您的累加器在哪里?请改用普通的 for…of 循环。
  • @Bergi - 但也是异步的,对吗?
  • 是的,保留await tempDic.save();。但是删除回调,iirc mongoose 方法不会返回一个承诺,如果你通过一个。
  • @Bergi 不幸的是,问题仍然存在——它们只是异步创建的,但不是按预期的顺序创建的(其他用法需要)。它也不会创建 Name3。

标签: javascript node.js asynchronous mongoose async-await


【解决方案1】:

一些需要改变的地方:

  • 不要使用reduce(您没有正确使用累加器)而是使用普通循环
  • 不要将回调传递给 save 方法以使其返回承诺
  • 其实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");
}

【讨论】:

    猜你喜欢
    • 2013-10-23
    • 2018-03-09
    • 2013-12-07
    • 2019-02-14
    • 2021-07-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-21
    相关资源
    最近更新 更多