【问题标题】:Cannot push into array from inside forEach loop无法从 forEach 循环内部推入数组
【发布时间】:2021-09-05 09:59:39
【问题描述】:

每当我尝试推入 pathItem 数组时,响应都是一个空数组。发生了什么?

        const categories = await Cars.find().distinct("bodytype");
        let pathItem = [];
        categories.forEach(async (element) => {
          const countQuery = await Cars.countDocuments({
            bodytype: element,
          });
          const numberOfPages = Math.ceil(countQuery / 12);
          for(let count=1; count<=numberOfPages; count++) {
          const carPath = {paths: { cartype: element, pages: count }}
            pathItem.push(carPath)
          }
        });
        console.log(pathItem) // this returns an empty array

【问题讨论】:

  • forEach 不会等待异步调用。使用for of
  • 您也可以使用Promise.all并行执行此操作
  • 非常感谢。这有帮助。不知道 forEach 不等待异步调用。
  • @greyShader 您能否为您的问题添加答案以帮助未来的问题访问者?

标签: javascript node.js arrays mongodb mongoose


【解决方案1】:

这是有效的:

        const categories = await Cars.find().distinct("bodytype");
        let pathItem = [];
        for(let elements of categories) {
          const countQuery = await Cars.countDocuments({
            bodytype: element,
          });
          const numberOfPages = Math.ceil(countQuery / 12);
          for(let count=1; count<=numberOfPages; count++) {
          const carPath = {paths: { cartype: element, pages: count }}
            pathItem.push(carPath)
          }
        });
        console.log(pathItem) // this does not returns an empty array anymore

正如 Tushar 提到的,forEach 不等待异步调用,因此在 forEach 退出每个循环之前 Mongoose 请求没有得到满足。

【讨论】:

    猜你喜欢
    • 2018-09-26
    • 2017-07-21
    • 2022-01-14
    • 2023-03-19
    • 1970-01-01
    • 2013-01-04
    • 2014-10-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多