首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >连接到Postgress时跳过连接

连接到Postgress时跳过连接
EN

Stack Overflow用户
提问于 2020-05-13 18:16:18
回答 1查看 43关注 0票数 0

我正在编写lambda函数,以连接到我在EC2实例上拥有的母版DB。我一直在使用'pg‘库来连接,就像他们的文档中所发现的那样,但是,我的函数一直跳过我的方法的创建连接段,只是继续和退出而没有完成任何事情。

代码语言:javascript
运行
复制
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。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-05-13 18:40:42

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

代码语言:javascript
运行
复制
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)
        })

    }
})

虽然,如果可以的话,可以创建一个承诺链,因为这样的管理可能更容易:

代码语言:javascript
运行
复制
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库在连接和查询上返回了什么。

希望这能有所帮助!

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61781948

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档