简体   繁体   English

推送在节点 js 中的 map function 中不起作用

[英]push is not working in map function in Node js

I m using Mongo DB and after getting result from aggregate query, map the result of that query and try to push result to array.我正在使用 Mongo DB,在从聚合查询中获取结果后,map 是该查询的结果,并尝试将结果推送到数组。 While consoling that array it returning an empty array, but if we console inside the map there are data s.在安慰该数组时,它返回一个空数组,但如果我们在 map 内进行控制台,则有 data s。 Below is my code snippet下面是我的代码片段

let house = await House.aggregate([
    { $group: { _id: "$houseNumber", count: { $sum: 1 } } },
    { $match: { _id: { $ne: null }, count: { $gt: 1 } } },
    { $project: { houseNumber: "$_id", _id: 0 } },
  ]);

  var arr = [];
  house.map(async (hNo) => {
    var house2 = await House.find(
      { houseNumber: hNo.houseNumber },
      "houseNumber"
    );
    arr.push(house2);
  });
  
  console.log(arr);

I m thinking async await making problem here.我在想异步等待在这里出现问题。 Please help me.请帮我。 Thank you so much.太感谢了。

Async function are not supported in.map map 不支持异步 function

You can use Promise.all to await every async function result.您可以使用Promise.all来等待每个异步 function 结果。

let house = await House.aggregate([
    { $group: { _id: "$houseNumber", count: { $sum: 1 } } },
    { $match: { _id: { $ne: null }, count: { $gt: 1 } } },
    { $project: { houseNumber: "$_id", _id: 0 } },
]);

// Array of Promises
const promises = house.map(hNo =>
    House.find(
        { houseNumber: hNo.houseNumber },
        "houseNumber"
    );
)

// Array with each promise result
const arr = await Promise.all(promises);
  
// Now you able to log it
console.log(arr);

While consoling that array it returning an empty array map is not waiting for an async function result, so at the moment of logging arr you have an empty array and arr.length pending Promises.在安慰该数组时,它返回一个空数组 map 不会等待异步 function 结果,因此在记录arr时,您有一个空数组和arr.length待处理的 Promises。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM