gpt4 book ai didi

javascript - 正确处理 promise 拒绝

转载 作者:行者123 更新时间:2023-12-02 23:41:14 25 4
gpt4 key购买 nike

考虑以下代码:

db.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 }

app.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 异步函数引发的。

处理此错误的正确方法(使用异步函数/箭头)是:

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();

关于javascript - 正确处理 promise 拒绝,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56062890/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com