0

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)

1
  • async/await has to be consistent from start to end. Both below answers are right. Commented Dec 29, 2020 at 16:04

2 Answers 2

2

If you're using async/await, you should not use .then() and must not pass callbacks to mongoose methods so that they return awaitable promises.

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;
}
Sign up to request clarification or add additional context in comments.

Comments

1
const loc_id = await LocationController.AddUserLocation(req.body.location.longitude
            , req.body.location.latitude, req.query.id)

I believe this should solve the issue. Since you are not waiting for the response from AddUserLocation therefore the control moves on and executes then().

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.