node.js - 快速等待数据库连接
问题描述
我在这里关注相关帖子
我正在努力等待从我的快速应用程序导入模块。
我知道要使用 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 };
})();
解决方案
一种选择是导出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
});
推荐阅读
- progressive-web-apps - 如何更改 Nuxt.js 中缓存控制的 max-age?
- html - 如何在 svelte 中渲染 html
- javascript - quickstart.js 中的连接问题
- c# - 为什么角色没有立即从动画“运行”移动到动画“空闲”,反之亦然?
- python - 将文本文件的行与另一个文件的每一行进行比较的条件语句
- java - 我应该在阶段的 catch 块中重新抛出异常吗?(脚本化管道 Jenkinsfile)
- ios - 带有 AVPro 播放器 (ios) 的 Unity 中 Vimeo Player Editor 自适应模式的问题
- c# - 加载 Blazor 客户端应用程序时如何避免浏览器中出现 System.TypeLoadException 未处理的异常
- python-3.x - DEAP:遗传算法 - 评估函数
- command-line-interface - 如何找到 compress-cli 的手册页?