0

A colleague want to refactor the backend code of a project into Async/Await, which I barely ever used.

I know how it works, but it's kind of strange to write code this way at the beginning.

router.post("/register", async (req, res) => {
  const { firstName, lastName, email, password } = req.body;

  bcrypt.hash(password, 10).then((hash) => {
    User.create({
      firstName: firstName,
      lastName: lastName,
      email: email,
      password: hash,
    });
    res.json("User created!");
  });
});

How would you refactor this simple piece of code, for example? Thanks!!!

4
  • 6
    const hash = await bcrypt.hash(password, 10); the rest should be self explanatory Commented Jun 30, 2021 at 9:57
  • 1
    @JaromandaX and the entire code in the then is them moved after that line. Commented Jun 30, 2021 at 9:58
  • well, yes, self explanatory @VLAZ :p especially since the OP says "I know how it works" Commented Jun 30, 2021 at 9:59
  • @JaromandaX wrote the comment before I saw the edited the comment. But I agree. Commented Jun 30, 2021 at 10:00

2 Answers 2

1

Probably like this:

router.post("/register", async (req, res) => {
    const { firstName, lastName, email, password } = req.body;
    
    const hash = await bcrypt.hash(password, 10);
    User.create({
        firstName: firstName,
        lastName: lastName,
        email: email,
        password: hash,
    });
    res.json("User created!");
});
Sign up to request clarification or add additional context in comments.

Comments

1

You can do this by simply adding await while calling hash function

router.post("/register", async (req, res) => {
  const { firstName, lastName, email, password } = req.body;

  try {
    const hash = await bcrypt.hash(password, 10);
    User.create({
      firstName: firstName,
      lastName: lastName,
      email: email,
      password: hash,
    });
  } catch (e) {
    // --- "your .catch() method would go here" ---
  }

  res.json("User created!");
});

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.