首页 > 解决方案 > 如果从嵌套函数调用,则无法从 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;
    }   
}

我也试过this._connection_pools[0]_queryReplicaDB,但这不起作用。

query我在这个方法中直接尝试了随机数的东西,这个方法有效。

可能是什么问题?

标签: node.jsdatabasepostgresqlpgpool

解决方案


就我而言,代码是正确的,只是我传递了错误的对象类型。而不是传递 Query 对象

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

此函数应接受字符串类型作为查询

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

推荐阅读