【问题标题】:unable to get results from postgres in nodejs if callled from nested function如果从嵌套函数调用,则无法从 nodejs 中的 postgres 获取结果
【发布时间】:2021-10-15 09:55:40
【问题描述】:

我有 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 方法中直接尝试了随机数的东西,这个方法有效。

可能是什么问题?

【问题讨论】:

  • 在第一个查询函数中,您创建一个查询并且不传递它,而是传递 queryInfo。是故意的吗?
  • @RaniSharim,谢谢,它有效,我传递了错误的对象

标签: node.js database postgresql pgpool


【解决方案1】:

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

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

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

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

【讨论】:

    猜你喜欢
    • 2020-05-11
    • 2020-09-21
    • 2023-04-08
    • 1970-01-01
    • 2018-10-18
    • 2017-01-19
    • 2019-03-27
    • 2016-01-16
    • 1970-01-01
    相关资源
    最近更新 更多