问题描述
我正在尝试使用 bindNodeCallback 将 connection.query
转换为返回 observable 的函数。
const MysqL = require('MysqL2');
const { bindNodeCallback } = require("rxjs");
const connection = MysqL.createConnection({host:"servername",user: "u",password:"p",database:"mydb" });
connection.connect();
let q = 'SELECT 1 from dual';
//1.This works. Default api
connection.query(q,(err,v)=>console.log(v));
//2.this throws: TypeError: Cannot read property 'config' of undefined
//bindNodeCallback(connection.query)(q).subscribe(v=>console.log(v));
//3.This returns a two dimensional array where the first element contains an array with the results and the second an array of ColumnDeFinition.
bindNodeCallback(connection.query).call(connection,q).subscribe(v=>console.log(v));
语句 1 打印: [ TextRow { '1': 1 } ]
语句 2 抛出: TypeError: Cannot read property 'config' of undefined
并且在调试代码之后我看到它引用了 this.config
(在 Connection 对象中),根据 the doc 需要调用输出函数时提供。
所以我将 this
添加到语句 3 但由于某种原因我没有得到我期望的:
声明 3 打印: [[ TextRow { '1': 1 } ],[ColumnDeFinition { _buf:...,_clientEncoding: 'utf-8'....]]
我的问题是,我应该如何使用 bindNodeCallback()
打印语句 1 打印的结果?
注意:如果您想使用旧版本的 MysqL
测试此问题,您可以使用 MysqL
而不是 MysqL2
,其中相同的问题仅发生在不同类型的 {{1} }}=>TextRow
和 RowDataPacket
=>ColumnDeFinition
解决方法
bindNodeCallback
将创建一个函数,该函数返回一个 observable,订阅将流式传输一个且仅包含以下内容的值:
- 传递给回调的参数(如果有)
-
array
的参数传递给回调(如果有多个)。
mysql
和 mysql2
向 query()
的回调传递两个参数:一个是包含结果的数组,另一个是包含列定义的数组。
验证调用 connection.query(q,(err,v,colDef)=>console.log(v,colDef));
以查看它还会打印列定义。
因此,由于参数是两个,传递给 subscribe 的函数应该接收一个数组,而不是单个参数。
“我应该如何使用 bindNodeCallback()
来打印语句 1 打印的结果?”
像现在一样调用它,只需从 map
传递以仅获取第一个参数(参数在回调参数数组的索引 0 处):
bindNodeCallback(connection.query).call(connection,q)
.pipe(map(arr=>arr[0])).subscribe(v=>console.log(v));