【问题标题】:Express await database connection快速等待数据库连接
【发布时间】:2019-03-14 21:02:07
【问题描述】:

我正在关注一个相关的帖子here

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

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

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

节点/快递:

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.js express async-await


    【解决方案1】:

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

    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
    });
    

    【讨论】:

    • 我的路线也在不同的模块中。当我将此模块导入这些路由模块时,如何在不每次都创建新连接的情况下保持数据库连接?我是否可以在每个模块中使用 .then 函数包装所有路由端点?
    • 重读后我的第二个问题得到了解答。我没有看到我们将客户端作为参数传递。
    • 应该不是问题 - 从 DB 模块导出的连接客户端 Promise 将在导入的任何地方引用相同的对象
    • 我真的很喜欢这个解决方案。谢谢
    猜你喜欢
    • 2021-10-06
    • 1970-01-01
    • 1970-01-01
    • 2021-08-17
    • 2023-02-03
    • 1970-01-01
    • 1970-01-01
    • 2018-01-17
    • 2013-11-20
    相关资源
    最近更新 更多