在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=>链接;,使用async链接(idk为什么这不起作用,我对loc_id有async,应该等到loc_id返回,但它没有(,我尝试了常规函数和async的不同组合,但没有得到想要的结果。(我使用异步和事件得到了一个结果,但没有监听器,我不知道那里发生了什么(

如果使用async/await,则不应使用.then(),也不得将回调传递给mongoose方法,以便它们返回await可执行的promise。

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;
}
const loc_id = await LocationController.AddUserLocation(req.body.location.longitude
, req.body.location.latitude, req.query.id)

我认为这应该能解决问题。由于您没有等待来自AddUserLocation的响应,因此控件继续移动并执行then((。

相关内容

最新更新