正确使用承诺等待和异步功能


router.post("/register", function (req, res) {
console.log(req.body);
// generate a salt
(async function(){

const salt = await bcrypt.genSalt(10);
// hash the password along with our new salt
const hash = await bcrypt.hash(req.body.txtPassword1, salt);
return hash;
})().then((data)=>{
var txtPassword = data;
let newUser = new userModel({
userName: req.body.txtUserName,
email: req.body.txtEmail,
profilePic: req.body.txtFileUpload,
password: txtPassword,
isAdmin: false
});
newUser.save((function (err) {
if (err) {
console.log("failed to save the new User ! : ", err);
} else {
console.log("New user has been added successfully with Id", newUser._id);
}
}))
req.flash('success', 'Registeration Successful');
console.log("Session value ", req.session);
console.log("value of txt password => ", txtPassword)
res.render("blogHome", { title: "Blogs || Home" });
});

}); 

我想知道这是否是使用 await 的正确方法。 我不得不采用这种方式,因为当我简单地尝试使用

var hash = await bcrypt.hash(req.body.txtPassword1,salt);

当我使用上面的代码时,我遇到了意外的标识符错误,当我用谷歌搜索时,我发现 await 必须在异步函数中使用,所以我将整个东西包装在 IIFE 端,并使用 .then(( 使用正常的 promise 处理 但我不知不觉中觉得我把一件简单的事情复杂化了。 谁能指出最简单的方法。 我被迫使用 promise 的原因是由于异步执行 数据库保存语句始终在计算哈希之前执行,这意味着密码为空,这反过来又触发了密码字段的架构验证

这是正确的,除了你没有处理错误,你需要这样做 - 否则,现在,你在控制台中得到一个"未处理的拒绝"错误,从一些即将推出的Node.js版本开始,它将终止未处理的拒绝过程。

但我不知不觉中觉得我把一件简单的事情复杂化了。

:-( 这是因为您正在处理一些基于 promise 的事情和一些基于旧式 Node 回调的事情。但是你可以通过承诺旧式回调的东西来使其更干净。

假设您更新了newUserModel.save,因此它返回了一个承诺,而不是具有 Node 样式的回调。然后:

router.post("/register", function (req, res) {
// generate a salt
(async function(){
const salt = await bcrypt.genSalt(10);
// hash the password along with our new salt
const txtPassword = await bcrypt.hash(req.body.txtPassword1, salt);
let newUser = new userModel({
userName: req.body.txtUserName,
email: req.body.txtEmail,
profilePic: req.body.txtFileUpload,
password: txtPassword,
isAdmin: false
});
await newUser.save(); // *** Assumes a new promise-enabled `save`
console.log("New user has been added successfully with Id", newUser._id);
req.flash('success', 'Registeration Successful');
console.log("Session value ", req.session);
console.log("value of txt password => ", txtPassword)
res.render("blogHome", { title: "Blogs || Home" });
})().catch(err => {
// handle error
});
});

如果这是 Express,你也可以查看 Koa(来自同一个人(,它可以让您进行整个post回调async并同时正确处理错误(使用中间件(。

将函数传递给router.postasync会更简单。您还可以考虑在通知注册成功之前等待保存新用户:

router.post("/register", async (req, res) => {
const salt = await bcrypt.genSalt(10);
// hash the password along with our new salt
const txtPassword = await bcrypt.hash(req.body.txtPassword1, salt);
const newUser = new userModel({
userName: req.body.txtUserName,
email: req.body.txtEmail,
profilePic: req.body.txtFileUpload,
password: txtPassword,
isAdmin: false
});
newUser.save((err) => {
if (err) return console.log("failed to save the new User ! : ", err);
console.log("New user has been added successfully with Id", newUser._id);
req.flash('success', 'Registeration Successful');
console.log("Session value ", req.session);
console.log("value of txt password => ", txtPassword)
res.render("blogHome", {
title: "Blogs || Home"
});
});
};

最新更新