judgejab
judgejab

Reputation: 529

Promises => Async/Await....Does this have any benefits?

I'm working through my express server controllers and refactoring from promises to async/await. For some of the functions, I'm unsure if I'm doing it just for the sake of it. If it's not any more readable, should I still do it?

Here's an example:

async sharedTroop(req, res, next) {
    const firebaseUID = req.params.uid;

    try {
      const user = await User.findOne({ firebaseUID }).select('troopPointTotal');

      user.troopPointTotal += 1000;

      try {
        user.save();
        try {
          res.send(user);
        } catch (e) {
          next(e);
        }
      } catch (e) {
        next(e);
      }
    } catch (e) {
      next(e);
    }
  }

Does the above (using async/await) have any benefits over this?:

sharedTroop(req, res, next) {
    const firebaseUID = req.params.uid;

    User.findOne({ firebaseUID })
      .select('troopPointTotal')
      .then(user => {
        user.troopPointTotal += 1000;
        user.save().then(() => res.send(user));
      })
      .catch(next);
  },

And if the refactoring hasn't improved readability, should I not bother?

Thanks!

Upvotes: 0

Views: 232

Answers (2)

Bergi
Bergi

Reputation: 665456

There's no reason to nest the try statements:

async sharedTroop(req, res, next) {
  const firebaseUID = req.params.uid;
  try {
    const user = await User.findOne({ firebaseUID }).select('troopPointTotal');
    user.troopPointTotal += 1000;
    user.save();
    res.send(user);
  } catch(e) {
    next(e);
  }
}

This might look a lot better than the nested callbacks of your then solution indeed. It also simplifies fixing your mistake: You will want to await the result of user.save() before sending the response - and then the catch will implicitly handle errors from the save process. In contrast, your then version has a similar mistake: by not returning the result of user.save().then(() => res.send(user)) from the callback, errors will not be handled by the .catch() in the end.

If the refactoring hasn't improved readability, should I not bother?

Sure, readability is subjective, and if you think there's no advantage then you should not bother to reactor.

Upvotes: 3

felixmosh
felixmosh

Reputation: 35583

Short answer NO, async/await is only a syntactic sugar for the code you wrote with then / catch.

The only benefit is order at your eyes. There is no need for callback, you mimic "synchronous" code style.

Upvotes: 2

Related Questions