node.js - node.js异步多个等待不适用于用户注册
问题描述
我正在尝试使用 async/await 重现此代码,但我不知道如何
.then.catch 链/巢
exports.signup = (req, res, next) => {
bcrypt.hash(req.body.password, 10)
.then(hash => {
const user = new User({
email: req.body.email,
password: hash
});
user.save()
.then(() => res.status(201).json({ message: 'Utilisateur créé !' }))
.catch(error => res.status(400).json({ error }));
})
.catch(error => res.status(500).json({ error }));
};
我想出尝试使用 async/await
exports.signup = async (req, res, next) => {
try {
const hash = await bcrypt.hash(req.body.password, 10);
const user = new User({
email: req.body.email,
password: hash
});
console.log(user);
let saveUser = await user.save();
console.log(saveUser);
res.status(201).json({ message: 'Utilisateur créé !'})
} catch (e) {
res.status(500).json({e})
}
};
我在控制台中获取用户,但代码在 user.save() 期间崩溃,因为我没有从 console.log(saveUser) 得到任何东西
我一直在阅读您可以将 await 函数堆叠到一个 try 块中,但也许在这里它不起作用,因为您需要
我试过分离 try/catch,要求我在 try 块之外初始化哈希,因为我将在第二次尝试中使用它,但它也不起作用。
按照 Nil Alfasir 的想法编辑后:
exports.signup = async (req, res, next) => {
try {
const hash = await bcrypt.hash(req.body.password, 10);
const user = new User({
email: req.body.email,
password: hash
});
console.log(user);
user.save();
return res.status(201).json({ message: 'Utilisateur créé !'})
} catch (e) {
return res.status(500).json({e})
}
};
但我在控制台中得到了这个
(node:43390) UnhandledPromiseRejectionWarning: MongoError: E11000 duplicate key error collection: myFirstDatabase.users index: username_1 dup key: { username: null }
.
.
.
(node:43390) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:43390) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
解决方案
推荐阅读
- r - 使用 Rmarkdown 编织到 pdf 时遇到麻烦
- python - AttributeError: _Connection__connection 使用 sqlalchemy 提交会话时
- bash - “期望”命令行脚本连接到 VPN 并输入密码
- node.js - api design - 如何设计公共 POST api 以防止垃圾邮件请求
- php - 如何在控制器 Laravel 7 中更改数据库中的日期格式
- matplotlib - 在 matplotlib 中绘制 2 个字典
- hash - 当 Sha256 和 md5 加在一起时
- c - '(struct student *)&st' 是一个指针;你的意思是使用'->'吗?|
- python - 在 3 个不同的集合中获得所有可能的组合
- c# - 如何知道一个 GameObject 在 Unity 中是否有网格?