node.js - 如何使用 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
有错误和未处理的承诺的处理程序,并进行日志记录(否则使用“替代”行)。所以引导模块只是引导系统。
解决方案
async
/await
这里是对 Promise 进行操作,所以你本质上是想通过调用.then
or来“启动”这个 Promise .catch
。
我的首选代码段是创建一个异步run
或main
函数,然后将错误处理附加到进程,如下所示:
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()
模式,因为您将来可能需要协调多个异步事物,这使代码更加明确。
推荐阅读
- c++ - 示例 Shell 应用程序显示的 V8“分段错误(核心转储)”错误
- java - REST API:URL 中的 JSON 对象以获取自定义 JSON
- akka - 类型为 2.6.3 的 akka 的日志记录问题
- python - 为什么我需要一个“返回”和一个新变量?
- ios - Fabric crashlytics 显示错误:致命异常:NSInternalInconsistencyException。在 IOS 应用程序中
- r - 如何从因子存储中提取特定值作为数据框中的列值
- kubernetes - kubelet 错误:更新节点租约失败
- javascript - XMLHttpRequest | 手动发送请求会得到 2111 个字符的响应,但使用 XMLHttpRequest 响应的长度为 179
- python-3.x - SyntaxError:python套接字编程中listen()的语法无效
- javascript - Reactjs如何从另一个JavaScript文件导入常量数组