node.js - 连接到 Postgress DB 时连接被跳过
问题描述
我正在编写一个 lambda 函数来连接到我在 EC2 实例上拥有的 postgress 数据库。我一直在使用他们的文档中的“pg”库进行连接,但是,我的函数一直跳过我的方法的建立连接部分,只是继续并退出而没有完成任何事情。
const client = new Client({
user: 'user',
host: 'xxxx.xxx.xxxx',
database: 'dbname',
password: 'password',
port: 5432,
})
client.connect(err => {
if (err) {
console.error('connection error', err.stack)
} else {
console.log('connected')
}
})
client.query('select count(*) from "Product"', (error, results) => {
if (error) {
console.log("Error when trying to query");
throw error
}
console.log(results.rows)
})
我完全按照“pg”文档所说的方法(https://node-postgres.com/features/connecting),但无法弄清楚这里出了什么问题。我正在使用无服务器和 nodejs12.x 来实现这个功能。
解决方案
在查询之前,您无需等待建立连接。试试这个:
const client = new Client({
user: 'user',
host: 'xxxx.xxx.xxxx',
database: 'dbname',
password: 'password',
port: 5432,
})
return client.connect(err => {
if (err) {
console.error('connection error', err.stack)
} else {
console.log('connected')
return client.query('select count(*) from "Product"', (error, results) => {
if (error) {
console.log("Error when trying to query");
throw error
}
console.log(results.rows)
})
}
})
虽然,如果可以的话,创建一个承诺链,因为它可能更容易管理,如下所示:
const client = new Client({
user: 'user',
host: 'xxxx.xxx.xxxx',
database: 'dbname',
password: 'password',
port: 5432,
})
return client.connect().then(()=>{
return client.query('select count(*) from "Product"')
}).then((results)=>{
console.log(results.rows)
}).catch((err)=>{
console.error('error', err.stack? err.stack : err)
})
如果可以的话,我说使用承诺链,因为我不确定 pg 库在连接和查询时返回什么。
希望这可以帮助!
推荐阅读
- python - 将列表拆分为行
- android - 用户无法在 Play 商店中评价/评论我的应用程序
- javascript - 如何根据用户输入过滤 Angular 视图中的数据?
- python - 在 Paraview 的自定义过滤器中导入日志记录
- django - 无法在 Windows 10 中运行 Django
- python-3.7 - asyncpg.exceptions.DataError:查询参数的输入无效
- java - 我正在尝试连接到远程服务器上的服务并且无法使其工作
- java - 从 MySQL 检索到的 TemporalType.TIMESTAMP 错误
- dax - 创建一个 Dax 度量以获取平均值
- html - 如何为同一个 HTML 文件中的两个按钮创建两个单独的 POST 方法?