首页 > 解决方案 > 如何使用 Node Express “一直异步”?

问题描述

我的系统中有很多异步功能,所以我需要“一直异步”,也就是http.Server创建express.Application应用程序的地方。

(这在异步系统中是不可避免的 - 构造函数中需要许多异步例程,这是无法完成的,因此我们需要使用异步工厂函数,这会导致异步一直蔓延到入口点.)

但我不确定用于引导应用程序的 Node/TypeScript 语法。

我的主要切入点是System.ts

class default export System {

  public constructor() {
    // init Express.Application
    // init http.Server
    // init other parts of the system
  }

  public async start(): Promise<void> {
    // start the system asynchronously
    // start listening with http.Server
  }

}

然后我有一个引导模块Main.ts

import System from "./System"
const system = new System();
export default ???;                      // PROBLEM IS HERE

应该运行哪个:

node ./dist/Main.js

但我不确定在导出行中使用什么。我尝试了所有这些:

export default await system.start();     // doesn't compile (obviously)
export default system.start();           // doesn't seem right
export default system.start().then();    // this works *maybe*

最后一行基于冒烟测试工作 - 但我不确定这是否是这样做的方法,以及是否有可能失败的东西。

启动异步节点应用程序的规范方法是什么?


更新
基于@JacobGillespie 的回答,Main.ts引导模块现在是:

import System from "./System"
new System().start().then();
//new System().start().catch(e => console.error(e));  // alternative

在我的情况下,System.ts有错误和未处理的承诺的处理程序,并进行日志记录(否则使用“替代”行)。所以引导模块只是引导系统。

标签: node.jstypescriptexpressasync-await

解决方案


async/await这里是对 Promise 进行操作,所以你本质上是想通过调用.thenor来“启动”这个 Promise .catch

我的首选代码段是创建一个异步runmain函数,然后将错误处理附加到进程,如下所示:

async function run() {
  // run the app, you can await stuff in here
}

run().catch(err => {
  console.error(err.stack)
  process.exit(1)
})

在您的情况下,看起来像(Main.ts):

import System from "./System"

async function run() {
  const system = new System()
  await system.start()
}

run().catch(err => {
  console.error(err.stack)
  process.exit(1)
})

你不需要导出任何东西,因为这个模块文件没有被导入到其他任何地方(它是入口文件)。

您可以只调用system.then()or system.catch(),但我个人喜欢这种async function run()模式,因为您将来可能需要协调多个异步事物,这使代码更加明确。


推荐阅读