Home > Enterprise >  How to switch back to async/await?
How to switch back to async/await?

Time:12-13

I am new to async/await so I have an exercise like below code, I have converted this code to async/await many times and still no success. Please help me. Thanks very much!

My code is as follows:

exports.register = (req, res) => {
  const user = req.body;

  try {
    // Validate the registration form
    validateRegisterForm(user)
      .then((response) => {
        // If response is true, hash the password
        if (response) {
          Md5Password(user.password)
            .then(async (hash) => {
              const { name, email } = user;
              const newUser = new User({
                name,
                password: hash,
              });

              // Save the user
              const savedUser = await newUser.save();
              res.status(200).json(savedUser);
            })
            .catch((error) => {
              res.status(500).json({
                message: error.message,
                err: "500: Internal Server Error",
              });
            });
        }
        // But if response is false, show the error message
        else {
          res.status(401).json({
            message: errorMessage(),
            error: "401: Unauthorized",
          });
        }
      })
      .catch((error) => {
        res.status(500).json({
          message: error.message,
          err: "500: Internal Server Error",
        });
      });
  } catch (error) {
    res.status(500).json({
      error: error.message,
      message: "registration failed",
      e: "500: Internal Server Error",
    });
  }
};

Please help me, thanks a lot!

CodePudding user response:

Not sure exactly what you're trying to achieve, but here's a version of your code with async/await:

exports.register = async (req, res) => {
    const user = req.body;

    try {
        // Validate the registration form
        const response = await validateRegisterForm(user);
        // If response is true, hash the password
        if (response) {
            const hash = await Md5Password(user.password);
            const { name, email } = user;
            const newUser = new User({
                name,
                password: hash,
            });
            // Save the user
            const savedUser = await newUser.save();
            res.status(200).json(savedUser);
        } else {
            res.status(401).json({
                message: errorMessage(),
                error: "401: Unauthorized"
            });
        }
    } catch (e) {
        res.status(500).json({
            message: e.message,
            err: "500: Internal Server Error"
        });
    }
}
  • Related