javascript - 为什么我的异步函数返回一个空数组?

标签 javascript node.js express mongoose async-await

我试图通过将用户的匹配项插入一个数组并返回该数组来获取用户的匹配项,以便我的路由器可以将数据发送到前端。但我的异步函数有一个问题:我只有一个空数组。我尝试设置一些断点,我注意到我的路由器在我的服务将数据推送到数组之前发送了数据。

这是我的路由器代码:

router.get("/allMatchs", auth, async (req, res) => {
  const user = await userService.getUserById(req);
  const matchs = await service.getMatchsByUser(user);
  res.send(matchs);
});

这是我的服务代码:

async function getMatchsByUser(user) {
  const userMatchs = user.matchs;
  let matchs;
  await userMatchs.map(async (m) => {
    let match = await Match.findById(m._id).select([
      "-isConfirmed",
      "-isUnmatched",
    ]);
    matchs.push(match);
  });
  return matchs;
}

感谢您的帮助。

最佳答案

这是因为.map()不支持async。它不会等待回调返回的 promise 。所以,当你这样做时:

await userMatchs.map(...) 

.map() 返回一个数组。您正在对一个 promise 数组调用await(请记住,.map() 返回一个数组)。这没有任何用处。它不会等待任何事情,.map() 内的各个迭代也不会等待。

您可以切换到普通的 for 循环,因为 for 循环是 Promise 感知的,并且它会正确 await 或者您可以使用 >等待 Promise.all(userMatchs.map(...)) .

你可以这样做:

function getMatchsByUser(user) {
  return Promise.all(user.matchs.map((m) => {
    return Match.findById(m._id).select([
      "-isConfirmed",
      "-isUnmatched",
    ]));
  });
}

或者,如果您想一次按顺序向数据库发出一个请求,请使用普通的 for 循环,其中 await 将在其中工作:

async function getMatchsByUser(user) {
  let matchs = [];
  for (let m of user.matchs) {
    let match = await Match.findById(m._id).select([
      "-isConfirmed",
      "-isUnmatched",
    ]);
    matchs.push(match);
  }
  return matchs;
}

关于javascript - 为什么我的异步函数返回一个空数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61787882/

相关文章:

node.js - 通过 consolidate.js 与 Swig 一起使用 Node.js Express 3.x 模板继承时出现问题

node.js - 从 javascript 回调获取数据的正确方法

javascript - JQuery 处理交互内容

javascript - JSON 数据不使用 .html() 显示

javascript - jquery 的 live 问题

mysql - aws rds 代理从 nodejs12.x 抛出超时错误

javascript - 基于开关的 url 重定向

node.js - npm list 如何知道哪些是直接依赖项?

mysql - 使用express ejs获取MySQL数据

node.js - 如何默认将错误返回为 JSON 而不是带有 express 的 HTML?