数组"/>
为什么我的异步函数返回一个空数组
因此,我试图通过将用户的匹配项推入数组并返回该数组来获取用户的匹配项,以便我的路由器可以将数据发送至前端。但是我的异步函数有问题,我只是有一个空数组。我曾尝试设置一些断点,但在我的服务将数据推送到阵列之前,我注意到路由器已发送数据。
有我的路由器代码:
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()
更多推荐
为什么我的异步函数返回一个空数组
发布评论