I have two functions that depend on each other. After my user saves his profile, I first have a function that saves his location and then returns its id, which I then use to update the user. But after trying a lot of combinations I couldn't get it to work properly. I'll list below what I tried.
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
});
}
Then is called before create
info: Then undefined {"service":"user-service"}
info: Created + 5feb3174f70c08f9543fdc49 {"service":"user-service"}
I tried using events, chaining it with then =>, chaining with asyncs (idk why this doesnt work, I had async for loc_id, and that should wait until loc_id returns but it doesnt), I tried different combinations of regular functions and asyncs but nothing gave me the desired result. (I have gotten a result using async and events but without listeners, I have no idea what happened there)