简体   繁体   English

Nodejs异步设置function

[英]Nodejs async setup function

I am currently switching from Nodejs v12 to v14 and it seems that v14 does not wait for the setup function to resolve anymore.我目前正在从 Nodejs v12 切换到 v14,似乎 v14 不再等待设置 function 解决。 I use Nodejs combined with Express.我将 Nodejs 与 Express 结合使用。 My code looks like this (simplified):我的代码看起来像这样(简化):

setup().then(context => {
    // app setup based on context 

    app.listen(8080)
})

Is there a prefered way to use an async setup function before initializing the rest of the application?在初始化应用程序的 rest 之前,是否有首选的方法来使用异步设置 function?

The setup function connects the database and return a single promise like so:设置 function 连接数据库并返回单个 promise,如下所示:

function setup() {
    // This is a postgres library that return a promise
    return db.connect(this.config);
}

On Node v12 it seems to await the promise and start listening on the specified port after it is done.在 Node v12 上,它似乎在等待 promise 并在完成后开始监听指定的端口。 However when I switch to version 14 it does not await the promise and gives a clean exit.但是,当我切换到版本 14 时,它不会等待 promise 并给出一个干净的退出。

Did you try using async/await?您是否尝试过使用异步/等待?

Try modifying function as shown below尝试修改 function 如下图

async function setup() {
  
  await db.connect(this.config);
  
  app.listen(8080)

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM