【发布时间】:2021-04-06 03:38:34
【问题描述】:
我有两个相互依赖的函数。在我的用户保存他的个人资料后,我首先有一个函数来保存他的位置,然后返回它的 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 => 链接它,用 asyncs 链接(idk 为什么这不起作用,我对 loc_id 有异步,应该等到 loc_id 返回但它没有返回),我尝试了常规函数的不同组合和异步但没有给我想要的结果。 (我使用 async 和 events 得到了结果,但没有监听器,我不知道那里发生了什么)
【问题讨论】:
-
async/await 必须从头到尾保持一致。以下两个答案都是正确的。
标签: javascript node.js asynchronous mongoose async-await