gpt4 book ai didi

javascript - node.js 使用 mongoose 链接多个异步函数

转载 作者:行者123 更新时间:2023-12-01 02:33:33 25 4
gpt4 key购买 nike

我有一个看起来像这样的函数,至少现在它可以工作。

exports.changePassword = (req, res) => {
const { token, password, confirmPassword } = req.body

User.findOne({resetPasswordToken: token}, (err, user)=>{
if(!user){
return res.status(400).send({
msg: 'Invalid token or token has been used!'
})
}

const hash_password = bcrypt.hashSync(password, 10)
User.findOneAndUpdate({_id: user._id},
{hash_password},
(err, result)=>{

if(err){
return res.status(400).send({
msg: err
})
}

User.findOneAndUpdate({_id: user._id},
{resetPasswordToken: ''},
(err, result)=>{
if(err){
return res.status(400).send({
msg: err
})
}

res.status(200).json({
status: 1,
data: 'Your password has been changed.'
})
}
)
})
})
}

我只是觉得写这段代码很糟糕,因为我认为它有几个问题:

  1. 回调 hell
  2. 错误处理代码重复

对于第一个问题,也许我可以使用完成参数?并做一些链接?有时我怀疑我是否需要处理每一个错误回调。您将如何重写上面的函数以使其变得更加优雅?

最佳答案

您可以将 Promise 与 Mongoose 结合使用,这将有助于解决回调 hell 问题:

exports.changePassword = (req, res) => {
const { token, password, confirmPassword } = req.body

User.findOne({resetPasswordToken: token}).then((user)=>{
// do stuff with user here

const hash_password = bcrypt.hashSync(password, 10)
// Now chain the next promise by returning it
return User.findOneAndUpdate({_id: user._id}, {hash_password});
}).then((result)=>{
// Now you have the result from the next promise, carry on...
res.status(200).json({
status: 1,
data: 'Your password has been changed.'
})
}).catch(err => {
// Handle any errors caught along the way
});
}

由于这些都是 promise ,因此您实际上可以使用 ES6 async/await 语法使其变得更加简洁:

// Note this now has the async keyword to make it an async function
exports.changePassword = async (req, res) => {
const { token, password, confirmPassword } = req.body

try {
// Here is the await keyword
const user = await User.findOne({resetPasswordToken: token});

// do stuff with user here

const hash_password = bcrypt.hashSync(password, 10)

// Now the next promise can also be awaited
const result = await User.findOneAndUpdate({_id: user._id}, {hash_password});

// Finally send the status
res.status(200).json({
status: 1,
data: 'Your password has been changed.'
});
} catch (err) {
// Any promise rejections along the way will be caught here
});
}

关于javascript - node.js 使用 mongoose 链接多个异步函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48128300/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com