这是我的代码:
我声明了一个变量(newSeller),我希望在过程中使用它
let newSeller = '';
if (req.body.selectSeller == '') {
User.findOne({email: req.body.sellerEmail}).then(userEx => {
if (!userEx) {
const newUser = new User({
firstName: req.body.sellerName,
lastName: req.body.sellerLastName,
title: req.body.sellerTitle,
phoneNumber: req.body.sellerPhNum,
email: req.body.sellerEmail,
password: req.body.password,
address: req.body.sellerAddress
});
bcrypt.genSalt(10, (err, salt)=>{
bcrypt.hash(newUser.password, salt, (err, hash)=>{
newUser.password = hash;
});
});
newUser.save().then(savedSeller => {
newSeller = savedSeller.id;
});
} else if (userEx) {
req.flash('error_message', 'this email already exists. try another one')
res.redirect('/admin/invoice/incoming');
}
});
} else {
newSeller = req.body.selectSeller;
}
这段代码实际上成功地保存了预期的文档,但是当我将变量(newSeller)分配给ES6 Promise的值时(then()之后),它将无法正常工作! 你能帮我吗?
如何获取保存的用户值?
答案 0 :(得分:1)
基本上,您在各个地方同时使用了异步和同步功能,这使所有事情变得混乱。基本上,如果在整个模块中甚至使用一个异步功能,就不能使用同步功能。但是再在异步函数中,尝试使用基于Promise的语法或async-await
假设您正在以某种明确的方式使用代码,那么可以通过以下方法简化代码(为便于理解,请注意以下内容):
app.post('/someroute', async (req, res) => { //<<-Async handler
let newSeller = '';
if (req.body.selectSeller == '') {
try { //<<--need to catch `async-await` errors
const userEx = await User.findOne({ email: req.body.sellerEmail });//<<awaiting the result
if (!userEx) {
const newUser = new User({
firstName: req.body.sellerName,
lastName: req.body.sellerLastName,
title: req.body.sellerTitle,
phoneNumber: req.body.sellerPhNum,
email: req.body.sellerEmail,
password: req.body.password,
address: req.body.sellerAddress
});
const salt = await bcrypt.genSalt(10); // await
const hash = await bcrypt.hash(newUser.password, salt);// await
newUser.password = hash;
const savedSeller = await newUser.save(); //await
newSeller = savedSeller.id;
} else {
req.flash('error_message', 'this email already exists. try another one')
res.redirect('/admin/invoice/incoming');
}
} catch (err) { //<<--if there is an error
req.flash(...something...)
res.redirect(...somewhere...);
}
} else {
newSeller = req.body.selectSeller;
}
//do something with newSeller
})