【发布时间】:2020-08-30 10:16:46
【问题描述】:
我试图通过将用户推送到数组中并返回该数组来获取用户的匹配项,以便我的路由器可以将数据发送到前端。但是我的异步函数有一个问题:我只有一个空数组。我尝试设置一些断点,但我注意到我的路由器在我的服务将数据推送到数组之前发送了数据。
这是我的路由器代码:
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。它不会等待回调返回的承诺。您可以切换到普通的for循环,因为forloop 是承诺感知的,它会正确地await或者您可以使用await Promise.all(userMatchs.map(...))。 -
仅供参考,使用
.map()有点傻,但仍然手动执行matchs.push(match)。当您想要从.map()返回的数组时,您使用.map(),而您完全忽略了该数组。否则,只需使用for循环。 -
也许你没有看到,但我在我的回答中提供了这个信息的一个更扩展的版本,包括几个不同的实现选择。
标签: javascript node.js express mongoose async-await