首页 > 解决方案 > 正确处理 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.

我该如何正确处理?

标签: javascriptnode.jsasynchronous

解决方案


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

推荐阅读