如何使用 .map() 和 mongoDB 调用修复 MERN 中的异步等待



My react component componentWillMount(( 发出一个 axios 调用,发送一个对象数组。我的节点/快速 API 收到请求。我想映射发送的数组,找到用户用户名与mongoDB调用我的用户集合。然后我想在名为 username 的对象中创建一个新属性并将其设置为结果。我需要等待我的映射函数完成,然后再将新的映射数组发送回前端。我正在使用异步等待和Promise.all((。我的前端正在接收一个空对象数组。

我试过只使用常规承诺,但也没有运气。我通过在您的方法上使用关键字 async 来理解异步等待的概念,并且基本上等待您使用的任何内容 await 继续前进。也许我的解释是错误的,只是似乎想不通。异步/等待和承诺是相当新的。

exports.getAuthorUserNames = async (req, res) => {
if (req.body.data) {
let mappedArr = req.body.data.map(nade => {
User.findOne({ _id: nade.authorID }, function(err, result) {
if (err) {
res.sendStatus(500);
} else {
nade.username = result.username;
}
});
});
res.status(200).send(await Promise.all(mappedArr));
}
};

除了结果之外,我返回一个对象数组,其中包含一个名为用户名的新属性,用户名从 result.username(db 调用(获得。我收到一个空数组。

exports.getAuthorUserNames = async (req, res) => {
try{
if (req.body.data) {
const mappedArr = req.body.data.map(nade => User.findOne({ _id: nade.authorID }));
const results = await Promise.all(mappedArr);
return res.status(200).send(results);
}
} catch(e){
//handle exception here
}
};
exports.getAuthorUserNames = async (req, res) => {
if (req.body.data) {
let mappedArr = req.body.data.map(async nade => {
await User.findOne({ _id: nade.authorID }).then(result => {
nade.author = result.username;
});
return nade;
});
res.status(200).send(await Promise.all(mappedArr));
}
};

最新更新