我试图通过将用户的匹配项插入一个数组并返回该数组来获取用户的匹配项,以便我的路由器可以将数据发送到前端。但我的异步函数有一个问题:我只有一个空数组。我尝试设置一些断点,我注意到我的路由器在我的服务将数据推送到数组之前发送了数据。
这是我的路由器代码:
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
。它不会等待回调返回的 promise 。所以,当你这样做时:
await userMatchs.map(...)
.map()
返回一个数组。您正在对一个 promise 数组调用await(请记住,.map()
返回一个数组)。这没有任何用处。它不会等待任何事情,.map()
内的各个迭代也不会等待。
您可以切换到普通的 for
循环,因为 for
循环是 Promise 感知的,并且它会正确 await
或者您可以使用 >等待 Promise.all(userMatchs.map(...))
.
你可以这样做:
function getMatchsByUser(user) {
return Promise.all(user.matchs.map((m) => {
return Match.findById(m._id).select([
"-isConfirmed",
"-isUnmatched",
]));
});
}
或者,如果您想一次按顺序向数据库发出一个请求,请使用普通的 for
循环,其中 await
将在其中工作:
async function getMatchsByUser(user) {
let matchs = [];
for (let m of user.matchs) {
let match = await Match.findById(m._id).select([
"-isConfirmed",
"-isUnmatched",
]);
matchs.push(match);
}
return matchs;
}
关于javascript - 为什么我的异步函数返回一个空数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61787882/