如果从嵌套函数调用,则无法在nodejs中从postgres获取结果



我有DB类,它有公共静态query方法。可以有多个连接池保存在_coonection_pools,所以我创建一个随机数,然后得到池和执行查询。这是代码

static async query(queryInfo: Query): Promise<any> {
const query = `select * from ${queryInfo.name} ${queryInfo.arguments} as info;`;
try {
return this._queryReplicaDB(queryInfo);
} catch (err) {
console.log("err", err);
throw err;
}
}
static async _queryReplicaDB(query: Query): Promise<any> {
const randomNumber = Math.floor(Math.random() * this._connection_pools.length);

// get the pool using random number
const pool = this._connection_pools[randomNumber];
try {
const response = await pool.query(query);
return response.rows[0].info;
} catch {
let response;
// if replica db fails then try with other pools
for (let i = 0; i < this._connection_pools.length; i++) {
// iterrate through every pool
const pool = this._connection_pools[i];
try {
response = await pool.query(query);
break;
} catch {
console.log("Error in Pool index: ", i);
}
}
return response.rows[0].info;
}
}

这是响应数组

中返回空的rows

但是如果不调用嵌套的_queryReplicaDB对象,这就可以了

static async query(queryInfo: Query): Promise<any> {
const query = `select * from ${queryInfo.name} ${queryInfo.arguments} as info;`;
try {
const response = await this._connection_pools[0].query(query);
return response.rows[0].info;
} catch (err) {
console.log("err", err);
throw err;
}   
}

我在_queryReplicaDB中也尝试了this._connection_pools[0],但这不起作用。

我在query方法中直接尝试了随机数的事情,在这种方法中,这是有效的。

有什么问题吗?

在我的情况下,代码是正确的,只是我传递了错误的对象类型。而不是传递查询对象

static async _queryReplicaDB(query: Query): Promise<any> {

这个函数应该接受字符串类型作为查询

static async _queryReplicaDB(query: string): Promise<any> {

最新更新