mongodb js中取数成功后如何运行?

cu6pst1q  于 2023-01-08  发布在  Go
关注(0)|答案(1)|浏览(226)
let users_data = [];
try {
  let users = await chatModel.find({ users: isVerified.userId });
  users.forEach(function (doc) {
    doc.users.forEach(async function (user) {
      if (isVerified.userId !== user) {
        let result = await userModel.find({ _id: user }, { firstName: 1 });
        users_data.push({ id: user, name: result[0].firstName });
      }
      console.log("Users_data from try =>", users_data);
    });
  });

  console.log("Users data => ", users_data);
  res.render("chat-app", { users: users_data });
} catch (error) {
  users_data = "";
  console.log(error);
  console.log("Users data => ", users_data);
  res.render("chat-app", { users: users_data });
}

在上面的代码中,我想记录和呈现页面,一旦所有的数据都被提取,我怎么才能实现这一点

yi0zb3m4

yi0zb3m41#

你必须把所有的承诺存储在一个变量中,然后,在调用res.render之前等待所有的承诺,因为你是在嵌套数组中循环,所以我在答案中使用了Array.prototype.flatMap

let users_data = [];
try {
  const users = await chatModel.find({ users: isVerified.userId });
  const promises = users.flatMap(function (doc) {
    return doc.users.map(async function (user) {
      if (isVerified.userId !== user) {
        let result = await userModel.find({ _id: user }, { firstName: 1 });
        users_data.push({ id: user, name: result[0].firstName });
      }
      console.log("Users_data from try =>", users_data);
    });
  });

  await Promise.all(promises);
  console.log("Users data => ", users_data);
  res.render("chat-app", { users: users_data });
} catch (error) {
  users_data = "";
  console.log(error);
  console.log("Users data => ", users_data);
  res.render("chat-app", { users: users_data });
}

相关问题