首页 > 解决方案 > 快速等待数据库连接

问题描述

我在这里关注相关帖子

我正在努力等待从我的快速应用程序导入模块。

我知道要使用 await,它必须包装在 async 函数中。但是我不能将我的整个节点程序包装在一个异步函数中,因为它会在没有做任何有用的事情的情况下退出。

如何正确等待数据库连接?

节点/快递:

require('dotenv').config();
var express = require('express');
var loginRouter = require('./routes/login/login');
var app = express();

async() => {
    const { client } = await require('./db/db');
    app.use('/login', loginRouter);
    app.set('port', process.env.PORT || 3000);
    app.listen(app.get('port'));
    console.log('Server listening on port ' + app.get('port'));
}

数据库模块:

const { Client } = require('pg');

module.exports = (async() => {
    const client = new Client();
    await client.connect();
    return { client };
})();

标签: node.jsexpressasync-await

解决方案


一种选择是导出Promise解析为connected client的 a 。然后,当你导入它时,调用.then导入Promise的来访问连接的客户端:

const { Client } = require('pg');

const client = new Client();
module.exports = {
  clientProm: client.connect().then(() => client)
};

和:

const { clientProm } = require('./db/db');
clientProm.then((client) => {
  // do stuff with connected client
});

推荐阅读