node.js - 如何对函数使用 Node.js 承诺(执行查询时的 CassandraDB 驱动程序)
问题描述
我正在使用 Cassandra DB 驱动程序中的 client.stream() 来使用页面获取大型结果集,然后对于返回的每一行结果,我将其推送到在我的范围顶部定义的数组中。
查询完成后,我想返回我的数组,但它总是返回“未定义”,我猜是因为获取查询需要很长时间,所以 Javascript 在对象被填充之前继续执行 return 语句。
对于不熟悉这个驱动的人:client.stream 是一个函数,它需要一点时间来获取一些数据。在返回对象之前,我需要等待这个完成!
例如
function foo() {
var resultArray: [];
var query = "select username from users where userRank = 3";
client.stream(query, {prepare: true})
.on('readable' function () {
var row;
while (row = this.read()) {
resultArray.push(row.username);
}
})
.on('end', function () {
return obj; // The object only exists in this scope but cant return from here
});
}
当我调用它时,var returned = foo();
我得到undefined
了返回值。
解决方案
如果要使用stream
API,则需要创建自己的Promise
实例并在流结束时解析它。
自己缓冲所有行然后返回 a 是没有意义的Promise
,驱动程序可以为您做到这一点。如果您不担心所有这些行都在内存中的内存消耗,您可以执行以下操作:
// Disable paging
// NOTE: Memory consumption will depend on the amount of rows
// and the amount of concurrent requests
const options = { prepare: true, fetchSize: 0 };
const promise = client.execute(query, params, options);
有关更多信息,请参阅文档:https ://docs.datastax.com/en/developer/nodejs-driver/latest/features/paging/
推荐阅读
- postgis - 在QGIS中点击地图可以在Postgis中输入地图点吗?
- python - min_max_scaler.fit_transform:ValueError:使用序列设置数组元素
- java - 为什么 maven-compiler-plugin 排除禁用
- rest - 如何在同一端口上启用 TLS 服务 gRPC 和 REST
- flutter - (颤振/飞镖)字符串换行获取错误:语法错误:未终止的字符串。:未定义的位置
- npm - 我可以对 peerDependencies 有一个后备吗?
- javascript - 正则表达式替换查询参数(++、+- 和 +)中的前导加号字符?
- vue.js - 有没有办法在 beforeRouteEnter 中显示 bootstrap-vue $toast 反馈?
- python-3.x - 在 .exe python 项目中复制/粘贴文本
- git - 在源代码控制中存储第 3 方 DLL (Azure DevOps/TFS/Git)