最新消息: 电脑我帮您提供丰富的电脑知识,编程学习,软件下载,win7系统下载。

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

IT培训 admin 11浏览 0评论

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

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

有我的路由器代码:

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()

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

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

有我的路由器代码:

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()

发布评论

评论列表 (0)

  1. 暂无评论