提问者:小点点

我想把这个回调函数更改为async/await,但是我不知道如何更改


User.findOne({ email: email })
.then((savedUser) => {
  if (savedUser) {
    return res
      .status(422)
      .json({ error: "user already exists with that email" });
  }
  bcrypt.hash(password, 12).then((hashedpassword) => {
    const user = new User({
      email,
      password: hashedpassword,
      name,
      pic,
    });

    user
      .save()
      .then((user) => {
        res.json({ message: "saved successfully" });
      })
      .catch((err) => {
        console.log(err);
      });
  });
})
.catch((err) => {
  console.log(err);
});
});

我正在通过将一些回调函数更改为async/await来研究async/await。这段代码有两个catch错误,但我不知道如何将这段代码更改为async/await。


共2个答案

匿名用户

const saveUser = async (email,password,name,pic)=>{
try{
 const user = new User({
      email,
      password: await  bcrypt.hash(password, 12),
      name,
      pic,
    })

 const savedUser = await User.save()
 return savedUser 
 }catch(error){
 throw new Error(error)
 }
}

const findUser = async (email)=>{
try{
 const user = await User.findOne({ email: email })
 return user
 }catch(error){
  throw new Error(error)
 }
}


匿名用户

需要记住的一件关键事情是,您可以在promiseawaitasync关键字就像是强制函数返回promise)。

以下方法返回promise,因此您可以使用Await

  • user.findone(。。。)
  • BCrypt.Hash(。。。)
  • user.save()

重构后的代码如下所示:

async function functionName(...) {

    try {
        const savedUser = await User.findOne({ email: email });
    }
    catch (e) {
        //...
    }
    if (savedUser) {
        return res
            .status(422)
            .json({ error: "user already exists with that email" });
    }

    const hashedpassword = await bcrypt.hash(password, 12)
    const user = new User({
        email,
        password: hashedpassword,
        name,
        pic,
    });

    try {
        await user.save();
    }
    catch (e) {
        return res
            .status(422)
            .json({ error: "...ERROR..." });
    }
    res.json({ message: "saved successfully" });

}