我正在编写lambda函数,以连接到我在EC2实例上拥有的母版DB。我一直在使用'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。
发布于 2020-05-13 18:40:42
在查询之前,您不需要等待建立连接。试试这个:
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库在连接和查询上返回了什么。
希望这能有所帮助!
https://stackoverflow.com/questions/61781948
复制相似问题