You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Node.js使用pg模块Promise时出现错误,寻求技术协助

解决Node.js中pg模块使用Promise时的await错误

你遇到的核心问题是在CommonJS模块的顶层代码直接使用了await——这是JavaScript的语法限制:在默认的CommonJS模块(.js后缀)里,await只能放在async函数内部,不能直接写在顶层作用域里,和pg模块本身无关。

下面给你两种可行的修复方案,附带最佳实践:

方案一:用async函数包裹代码(推荐,兼容所有Node.js版本)

把所有异步操作放进一个async函数里,同时加上错误捕获和连接关闭的逻辑,避免资源泄漏:

const { Client } = require('pg')

async function executeDatabaseQuery() {
  const client = new Client({ 
    host: 'localhost', 
    port: 5432, 
    user: 'user1', 
    password: 'pass1', 
    database: 'staging' 
  })

  try {
    // 建立连接
    await client.connect()
    console.log("connected")

    // 执行查询
    const x = await client.query("select * from phaas_global.organization")
    console.log("x=")
    console.log(x)
  } catch (error) {
    // 捕获连接或查询过程中的错误
    console.error('数据库操作失败:', error)
  } finally {
    // 无论成功失败,都关闭连接
    await client.end()
    console.log("连接已关闭")
  }
}

// 调用函数
executeDatabaseQuery()

方案二:改用ES模块支持顶层await

如果你想用顶层await,可以切换到ES模块:

  1. 要么把文件名改成pg1.mjs
  2. 要么在项目根目录的package.json里添加"type": "module"

修改后的代码可以保留顶层await,但同样建议加上错误处理和连接关闭:

import { Client } from 'pg'

const client = new Client({ 
  host: 'localhost', 
  port: 5432, 
  user: 'user1', 
  password: 'pass1', 
  database: 'staging' 
})

try {
  await client.connect()
  console.log("connected")
  const x = await client.query("select * from phaas_global.organization")
  console.log("x=")
  console.log(x)
} catch (error) {
  console.error('数据库操作出错:', error)
} finally {
  await client.end()
}

额外提醒:永远不要忽略错误处理——如果数据库连接失败、查询语句有误,没有try/catch的话程序会直接崩溃;同时记得关闭连接,否则数据库连接池会被耗尽,影响后续操作。

内容的提问来源于stack exchange,提问作者pktCoder

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 08:45:40