0

I'm having some issues understanding why I'm getting the following results:

I have this function in UserService.js

async function addUser(username, divisionId, points){
    const newUser=new User({username: username, divisionId: divisionId, points:points});
    await newUser.save();//save is a function from mongoose which returns a promise
}

And this code in userController.js

router.route('/addUser').post((req, res) => {
  const username = req.body.username;
  const divisionId = req.body.divisionId;
  const points = 0;
  userService.addUser(username,divisionId, points)
    .then(() => res.json('User added!'))
    .catch((err=>res.status(400).json('Error '+ err)));
});

I have realized that if I remove the await in: await newUser.save() the exceptions wont be caught in the userController. I just can't seem to understand why; If .save() throws an exception shouldn't it propagate to addUser and be caught in the catch block? Should I keep the await? Isn't it bad to be waiting for something just for this purpose in an asynchronous context?

Sorry if this is a dumb question but I couldn't find anything that specifically addresses this propagation of exceptions in async contexts

1 Answers1

0

If you don't have the await in there, then newUser.save() just means "call the save function, and do nothing with the promise it returns". Once the promise has been created, addUser immediately finishes running and returns. addUser will not wait for the lost promise to resolve or reject.

Next, any code you've chained onto addUser will run. Since addUser resolved successfully, that will be the .then block, not the .catch. If the forgotten promise happens to throw sometime in the future, it won't have any effect; we've already moved on. Nothing called .catch on that promise, and nothing awaited it either, so there's no code to run.

Nicholas Tower
  • 72,740
  • 7
  • 86
  • 98