因此,我试图通过将用户的匹配项推入数组并返回该数组来获取用户的匹配项,以便我的路由器可以将数据发送至前端。但是我的异步函数有问题,我只是有一个空数组。我尝试设置一些断点,并注意到我的路由器在服务将数据推送到阵列之前发送了数据。
有我的路由器代码:
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(async (m) => {
let match = await Match.findById(m._id).select([
"-isConfirmed",
"-isUnmatched",
]);
matchs.push(match);
}); // -> return an array of promises
它返回一个promise数组,所以await
不会等待它执行,->返回空数组。
为此,您应该使用Promise.all()
像这样:
async function getMatchsByUser(user) {
const userMatchs = user.matchs;
let matches = await Promise.all(userMatchs.map(async (m) => {
return Match.findById(m._id).select([
"-isConfirmed",
"-isUnmatched",
]);
}));
return matches;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句