'How should I structure this code to run using .then in NodeJS and Express?

exports.postSignup = async (req, res, next) => {
  const firstName = req.body.firstName;
  const lastName = req.body.lastName;
  const email = req.body.email;
  const password = req.body.password;

  const errors = validationResult(req);
  if (!errors.isEmpty()) {
    console.log(errors.array());
    return res.status(422).render('auth/signup', {
      path: 'signup',
      pageTitle: 'Signup',
      errorMessage: errors.array()[0].msg,
      oldInput: {
        firstName: firstName,
        lastName: lastName,
        email: email,
        password: password,
        confirmPassword: req.body.confirmPassword
      },
      validationErrors: errors.array()
    });
  }

  bcrypt
    .hash(password, 12)
    .then(hashedPassword => {
      const user = new User({
        firstName: firstName,
        lastName: lastName,
        email: email,
        password: hashedPassword
      });
      return user.save();
    })
    .then(result => {

    if (req.session.cart) {
      const cart = await new Cart(req.session.cart);
      cart.save = req.user._id;
      await cart.save();
    }
      res.redirect('/login');
      const msg = {
        to: email, // recipient email
        from: { name: 'New User', email: '[email protected]' },
        templateId: process.env.WELCOME_TEMPLATE_ID
      }
      return sgMail
        .send(msg)
        .then(() => {
          console.log('Email sent')
        })
        .catch((error) => {
          console.error(error)
        })
    })
    .catch(err => {
      const error = new Error(err);
      error.httpStatusCode = 500;
      return next(error);
    });
};

An anonymous user can add items to cart. When they hit checkout, they're redirected to signup first before making a purchase. Now, I want to be able to check if the req has a session cart so I can register the user, then save that session cart in my Cart model so the cart session is lost. The code below is what I have so far. However, after a user signs up and try to checkout it seems the cart wasn't saved. I think there's a way to restructure the code but can't seem to get it. Any help will be appreciated!



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source