【发布时间】:2021-08-21 01:25:42
【问题描述】:
所以我在创建 postgres 类时遇到了问题。但是,当连接到我的数据库时,我注意到在构造函数之前调用了一个函数。这是我的代码
import { Client } from 'pg';
import { Config } from './config/postgres'
class PostgresHandler {
client: Client;
status: boolean | undefined = false;
constructor(){
this.client = new Client(Config)
this.client.connect(err => {
if (err) {
console.error('connection error', err.stack)
this.status = false
} else {
console.log('connected')
this.status = true
}
})
}
retreiveImageData() {
console.log(this.status)
}
}
export {PostgresHandler}
调用这个类
var psql = new PostgresHandler_1.PostgresHandler();
psql.retreiveImageData()
输出:
false
connected
如何让我的构造函数在类中的任何其他方法之前先运行? 我正在尝试与 postgres 建立连接并将连接状态设置为 true。
【问题讨论】:
-
请参阅How do I return the response from an aynchronous call,这是重复的。换句话说,显然构造函数必须首先运行——但是你在构造函数中调用了一个异步方法,该方法在未来的任意时间返回。
-
首先,正如其他人所解释的,您需要了解非阻塞、异步操作的工作原理以及这对您的编码意味着什么。然后,您可以阅读this answer 关于在构造函数中使用异步操作的信息,这些操作存在另一组问题,因为构造函数必须返回新对象,因此它不能轻易返回承诺让调用者知道异步操作何时完成.
标签: node.js typescript postgresql