【发布时间】:2018-09-05 06:43:35
【问题描述】:
所以我有一个函数可以对 MongoDB 数据库进行一系列异步调用。我想在所有调用完成后返回结果,但是下面的代码没有这样做。
const getMatchesInfo = async mongoDBUserIds => {
_.map(mongoDBUserIds, async mongoDBUserId => {
const user = await UserCollection.findOne({
_id: mongoDBUserId
});
console.log('user.profile.name = ', user.profile.name);
return user;
});
};
我在我的 Node.js API 中调用这个函数:
module.exports = app => {
app.get('/api/matches', requireLogin, async (request, response) => {
const mongoDBUserIds = request.query.mongoDBUserIds.split(',');
let matches_info = await getMatchesInfo(mongoDBUserIds); // <=== await here
console.log('matches_info = ', matches_info);
response.send(matches_info);
});
};
我不明白为什么matches_info 在函数getMatchesInfo 内部的console.logs 之前被打印出来?我认为await here 应该阻止它下面的代码运行,直到getMatchesInfo 返回。我不明白什么?
【问题讨论】:
标签: node.js mongodb mongoose async-await