微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

我想让我的路线等待所有要使用nodeJS完成的过程

如何解决我想让我的路线等待所有要使用nodeJS完成的过程

我有一条复杂的路线,我想用猫鼬修改我从数据库中获得的信息 当它结束我的项目的对象数组时,每个对象包含另一个集合女巫的ID数组,我必须为每个对象添加一个属性代码如下:

/* here i am trying to get the list of items */
let itemsList = await Items.find().lean();

/* Now i want to loop through them to go to each ones inner array of IDs */
itemsList.forEach(item => {

    /* here i am making a new object property to containg what the IDs pointing at */
    item.theProducts = [];
            
    /* Now i am going through the array of IDs */
    item.IDsArray.forEach(async product => {

        /* finding each product by the ID */
        let foundProduct = await SlemaniMaxzan.findById(product,{ _id: 0,productName: 1,productPrice: 1 }).lean();
        /* showing the product */
        console.log(foundProduct);        

        /* Now i am pushing it to the new property */
        item.theProducts.push(foundProduct);

    });
});

/* trying to check it the values has been added */
/* i expect the values has been added jsut fine,but it is not working */
console.log(itemsList);

res.render("mandubakan",{ title: "list",mandubakan: itemsList });

当我运行它时,它没有被添加,它只是为项目创建了一个新的空数组,但没有添加任何内容,并且程序甚至在记录每个foundProduct之前都记录了itemsList

解决方法

对于异步函数,必须避免使用方法forEach

尝试类似的事情:

let itemsList = await Items.find().lean();

for (let item of itemsList) {
  item.theProducts = [];
  for (let product of item.IDsArray) {
    let foundProduct = await SlemaniMaxzan.findById(product,{
      _id: 0,productName: 1,productPrice: 1,}).lean();

    console.log(foundProduct);
    item.theProducts.push(foundProduct);
  }
}
console.log(itemsList);
res.render("mandubakan",{ title: "list",mandubakan: itemsList });


版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?