javascript - 正确处理 Promise Rejections
问题描述
考虑以下代码:
数据库.js
// Connecting to catalogstore (mongodb)
const mydb = async () => {
try {
await mongoose.connect(process.env.db);
console.log("Connected to Database!");
}
catch (err) {
throw new Error("Database connection error:", err);
}
};
export { db }
应用程序.js
import { db } from './db';
db().then(async() => {
try {
let server = app.listen(process.env.port,
process.env.host, function() {
let host = server.address().address;
let port = server.address().port;
console.log('App started');
});
} catch (err) {
console.log(err);
}
});
基本上我只想在建立数据库连接后启动 Express 服务器。
它实际上工作正常,但是我收到此警告:
(node:29892) UnhandledPromiseRejectionWarning: Error: Database connection error:
at catalogstore (/Users/notaris/Workspace/Google/gcp-devops/apps/catalogservice/src/db.js:44:11)
at processTicksAndRejections (internal/process/task_queues.js:89:5)
(node:29892) 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:29892) [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.
我该如何正确处理?
解决方案
db
错误是由async 函数引发的。
处理此问题的正确方法Error
(使用异步函数/箭头)是:
import { db } from './db';
const main = async () => {
try {
await db();
let server = app.listen(process.env.port,
process.env.host, function() {
let host = server.address().address;
let port = server.address().port;
console.log('App started');
});
} catch (err) {
console.log(err);
}
});
main();
推荐阅读
- java - 如何执行 Assertions.assertAllFalse() 之类的操作?
- c# - 将 ConsoleColor 更改为十六进制值
- xcode - Xcode 12.3 更新后不断崩溃
- python - 使用 Boto3 的 S3 存储桶策略
- ios - Firebase 不为 Flutter 应用的 ios 部分收集推送通知的打开和转换数据
- rust - 是否可以列出为特定类型(变量)实现的所有特征?
- python - 无法在代理后面调用 SOAP 请求(不支持代理方案无)
- javascript - 如何向 WordPress 图像添加自定义类
- python - Jupyter 隐藏数据框索引但保留原始样式
- css - 在 django 中下载的字体不起作用