javascript - 在 Javascript/Nodejs、Mongoose 中链接多个异步函数,其中一个函数依赖于另一个函数
问题描述
我有两个相互依赖的功能。在我的用户保存他的个人资料后,我首先有一个函数来保存他的位置,然后返回它的 id,然后我用它来更新用户。但是在尝试了很多组合之后,我无法让它正常工作。我将在下面列出我尝试过的内容。
async function NewUserProfileUpdate(req) {
try {
const loc_id = LocationController.AddUserLocation(req.body.location.longitude
, req.body.location.latitude, req.query.id)
loc_id.then((id) => {
logger.info("Then " + id)
UserModel.User.updateOne({ user_id: req.query.id }, {
gender: req.body.gender, name: req.body.name, bio: req.body.bio,
location_id: id
})
})
} catch (err) {
return err
}
}
async function AddUserLocation(longitude, latitude, userID) {
const location = { type: 'Point', coordinates: [longitude, latitude] }
await LocationModel.create(
{ user_id: userID, location: location }, function (err, loc) {
if (err) {
return err;
}
logger.info("Created + " + loc._id)
return loc._id
});
}
然后在创建之前调用
info: Then undefined {"service":"user-service"}
info: Created + 5feb3174f70c08f9543fdc49 {"service":"user-service"}
我尝试使用事件,用 then => 链接它,用异步链接(idk 为什么这不起作用,我有 loc_id 的异步,应该等到 loc_id 返回但它没有),我尝试了常规函数和异步的不同组合但是什么都没有给我想要的结果。(我使用异步和事件得到了结果,但没有监听器,我不知道那里发生了什么)
解决方案
如果你正在使用async
/ await
,你不应该使用.then()
也不能将回调传递给 mongoose 方法,以便它们返回可行的await
承诺。
async function NewUserProfileUpdate(req) {
const location_id = await LocationController.AddUserLocation(req.body.location, req.query.id);
// ^^^^^
logger.info("Then " + location_id);
await UserModel.User.updateOne({ user_id: req.query.id }, {
// ^^^^^
gender: req.body.gender,
name: req.body.name,
bio: req.body.bio,
location_id,
});
}
async function AddUserLocation({longitude, latitude}, user_id) {
const location = { type: 'Point', coordinates: [longitude, latitude] };
const loc = await LocationModel.create({ user_id, location });
// ^ no callback
logger.info("Created + " + loc._id);
return loc._id;
}
推荐阅读
- sql-server - WHERE 子句中带有 CASE 的大于子句会显着降低查询速度
- reactjs - React useQuery 导致数据前后多次重新渲染
- ios - 如何在没有互联网的情况下从多个设备到单个设备进行通信
- mql4 - 无法让指标枢轴点与 EA 代码匹配
- visual-studio-code - Visual Studio Code 离线安装
- python - 如何在这个程序中实现循环?
- java - 在 Java 中填充 2D 数组并获取 ExceptionOutOfBounds
- algorithm - 从图像中检测笔记本电脑盖关闭的快速算法
- javascript - 什么时候可以删除函数的大括号?
- android - 本机崩溃 Android OS 8