fra.mstr
fra.mstr

Reputation: 55

Convert this Promise based code into Async / Await?

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!!!

Upvotes: 0

Views: 55

Answers (2)

subrahmanya bhat
subrahmanya bhat

Reputation: 598

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!");
});

Upvotes: 1

kaffarell
kaffarell

Reputation: 709

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!");
});

Upvotes: 1

Related Questions