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。
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)
}
}
需要记住的一件关键事情是,您可以在promise
上await
(async
关键字就像是强制函数返回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" });
}