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

编程入门 行业动态 更新时间:2024-10-11 13:25:12

为什么我的异步函数返回一个空<a href=https://www.elefans.com/category/jswz/34/1771288.html style=数组"/>

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

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

有我的路由器代码:

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;
}

谢谢您的帮助。

回答如下:

您的问题是userMatchs.map

将异步/等待与map()结合使用可能会有些棘手

How to use Async and Await with Array.prototype.map()

更多推荐

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

本文发布于:2024-05-07 13:50:07,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1756536.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   函数

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!