首页 > 解决方案 > 如何对函数使用 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了返回值。

标签: node.jsasynchronouscassandrapromisedatastax-enterprise

解决方案


如果要使用streamAPI,则需要创建自己的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/


推荐阅读