node.js - 如果从嵌套函数调用,则无法从 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
我在这个方法中直接尝试了随机数的东西,这个方法有效。
可能是什么问题?
解决方案
就我而言,代码是正确的,只是我传递了错误的对象类型。而不是传递 Query 对象
static async _queryReplicaDB(query: Query): Promise<any> {
此函数应接受字符串类型作为查询
static async _queryReplicaDB(query: string): Promise<any> {
推荐阅读
- c# - 运行单元测试时出现 System.TypeAccessException
- postgresql - 当我使用 orderBy 时,Doctrine QueryBuilder 会削减结果
- python - 如何在Django中使用注释找到特定值和总值之间的比率并将其存储在每个实体中?
- security - 用GraphicsMagick等效的policy.xml文件来处理像素洪水DOS攻击
- protractor - 在量角器中找不到 css 元素
- apache - Shibboleth 的反向代理不发送请求 POST
- java - CSV 文件中的数据挖掘和模式识别 (Python ML)
- office-js - 在 word 中使用 office-js 为段落编号
- javascript - 更改背景 Javascript 项目
- c# - 用字母变量替换数学方程中的浮点数