![](/img/trans.png)
[英]How do I go about changing the contents of a page based on the URL? Express.js, Node.js
[英]How do I go "async all the way down" with 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
这里有操作上的承诺,所以你基本上是要通过调用“开始”的承诺.then
或.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()
或system.catch()
,但我个人喜欢async function run()
模式,因为您将来可能需要协调多个异步事物,这使代码更加明确。
system.start().then() => {
value => export default value
}
在我看来,更好的方法是:System.ts:
function System():Promise<string>{
//setup express and the server
return new Promise((res,rej) => {
//the server var is just the http server instance
server.listen(8000,() => resolve("server created"));
});
}
export {System}
然后在 Main.ts 中:
import {System} from "yourpath"
进而:
System().then(() => {
//code runs when server is created
}).catch(err => console.error(err));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.