node.js - `UnhandledPromiseRejectionWarning: Unhandled Promise Rejection` 在我的节点应用程序中
问题描述
为了学习Node.js
,我学习了一个他们使用 async/await 的课程,如下所示:
exports.signup = async (req, res) => {
const userExists = await userExists.findOne({ email: req.body.email });
if (userExists) {
return res.status(403).json({
error: "Email is taken!"
});
} else {
const user = await new User(req.body);
await user.save();
return res.status(200).json({ user });
}
};
但它让我UnhandledPromiseRejectionWarning
崩溃了应用程序。
(node:10780) 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:10780) [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.
似乎我没有处理错误部分,但我用我的 else 块做了它,它不是这样工作的吗?
任何帮助将不胜感激。
解决方案
您需要await
通过将其包围来从语句中捕获任何被拒绝的承诺try/catch
。
exports.signup = async (req, res) => {
try {
const userExists = await User.findOne({ email: req.body.email });
if (userExists) {
return res.status(403).json({
error: "Email is taken!"
});
} else {
const user = new User(req.body);
await user.save();
return res.status(200).json({ user });
}
} catch(e) {
// some sort of internal error (probably database issue)
console.log(e);
res.sendStatus(500);
}
};
这也删除了await
in ,await new User(req.body)
因为await
只有当您await
承诺并且new User()
不是异步且不返回承诺时才会有用,因此没有理由使用await
它。
请注意,为了避免两个单独的请求可能都发现用户不存在并且两个请求都可能尝试创建一个的竞争条件,您需要确保您的用户电子邮件在数据库中配置为唯一键,以便您永远不会为同一封电子邮件获得重复的用户。这是服务器编程中的一个微妙之处,理解它以避免竞争条件很重要。
推荐阅读
- c# - 如何检索 Program.cs 中返回的访问令牌以在 Startup.cs 中可用?
- ios - Apple 拒绝 - ITMS-90338:非公共 API 使用 - databasePool:didAddDatabase:, databasePool:shouldAddDatabaseToPool:, ddSetLogLevel
- material-ui - Material-UI TextField:控制边框颜色
- python - 如果我们有多个条件,为什么 if 条件评估失败?
- apache - 从 Apache 代理反向中的重定向 URL 传递多个参数
- python-2.7 - 将任务的不同步骤记录到python中的单个文件中
- php - 为什么 Firefox 显示 HTML,但忽略了我的 PHP 代码
- java - 有没有更简洁的方法来实例化对象 A 的 5 个、对象 B 的 3 个、对象 C 的 1 个、对象 D 的 1 个,都在一个方法中?
- regex - 正则表达式:方括号之间存在一个字符串,不存在另一个
- electron - 在 Electron 中,如何打开不是 BrowserWindow 的窗口?