首页 > 解决方案 > 连接到 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 来实现这个功能。

标签: node.jspostgresqllambda

解决方案


在查询之前,您无需等待建立连接。试试这个:

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 库在连接和查询时返回什么。

希望这可以帮助!


推荐阅读