简体   繁体   中英

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM