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

pg包调用then函数报错:TypeError: Cannot read properties of undefined (reading 'then')

问题描述

调用pg客户端的connect后执行then时出现以下错误:

TypeError: Cannot read properties of undefined (reading 'then')
at Object.<anonymous> (/app/src/index.js:52:2)
at Module._compile (node:internal/modules/cjs/loader:1546:14)
at Module._extensions..js (node:internal/modules/cjs/loader:1691:10)
at Module.load (node:internal/modules/cjs/loader:1317:32)
at Module._load (node:internal/modules/cjs/loader:1127:12)

相关代码:

const { Client } = require('pg');

const PG_USER = 'root';
const PG_PASSWORD = 'example';
const PG_HOST = 'postgres';
const PG_PORT = '5432';
const PG_URI = `postgresql://${PG_USER}:${PG_PASSWORD}@${PG_HOST}:${PG_PORT}`;

const client =  new Client({
  connectionString: PG_URI,
});

client.connect(PG_URI)
  .then( () =>console.log('connect to postgresdb...'))
  .catch((err)=>console.log('failed connect to postgresdb:' ,err))
错误原因

pg的Client.connect()方法不接受连接字符串作为参数,它仅支持传入一个可选的回调函数。当你传入PG_URI时,方法会将其识别为回调函数,此时不会返回Promise对象,因此调用then时会触发“无法读取undefined的then属性”的错误。此外,你已经在初始化Client实例时传入了connectionString,connect方法无需重复传入连接信息。

解决方法

移除connect()方法的参数,直接调用无参的client.connect(),此时方法会返回Promise,可正常使用then/catch链式调用:

const { Client } = require('pg');

const PG_USER = 'root';
const PG_PASSWORD = 'example';
const PG_HOST = 'postgres';
const PG_PORT = '5432';
const PG_URI = `postgresql://${PG_USER}:${PG_PASSWORD}@${PG_HOST}:${PG_PORT}`;

const client =  new Client({
  connectionString: PG_URI,
});

// 去掉connect的参数PG_URI
client.connect()
  .then( () =>console.log('connect to postgresdb...'))
  .catch((err)=>console.log('failed connect to postgresdb:' ,err))

也可以使用async/await写法,提升代码可读性:

const { Client } = require('pg');

const PG_USER = 'root';
const PG_PASSWORD = 'example';
const PG_HOST = 'postgres';
const PG_PORT = '5432';
const PG_URI = `postgresql://${PG_USER}:${PG_PASSWORD}@${PG_HOST}:${PG_PORT}`;

const client =  new Client({
  connectionString: PG_URI,
});

async function connectDB() {
  try {
    await client.connect();
    console.log('connect to postgresdb...');
  } catch (err) {
    console.log('failed connect to postgresdb:', err);
  }
}

connectDB();

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 08:52:10