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

unable to get results from postgres in nodejs if callled from nested function

我有 DB class,它有 public 静态 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;
    }
}

响应数组

中return为空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> {