如何对函数使用 Node.js promises(执行查询时的 CassandraDB 驱动程序)

How to use Node.js promises for a function (CassandraDB driver when executing query)

我正在使用 Cassandra DB 驱动程序中的 client.stream() 使用页面获取大型结果集,然后对于每一行结果 returned 我将其推入定义在顶部的数组中我的范围。

查询完成后,我想 return 我的数组,但它总是 returns 'undefined' 我猜是因为获取查询需要很长时间所以 Javascript 在对象被填充之前继续执行 return 语句。

对于那些不熟悉这个驱动程序的人: client.stream 是一个函数,需要一些时间来获取一些数据。在 returning 对象之前,我需要等待它完成!

例如

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 作为 return 值。

如果您想使用 stream API,您需要创建自己的 Promise 实例并在流结束时解析它。

您自己缓冲所有行然后 return 一个 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/

为了补充答案,我能够 stream 在 Promise 中工作。

            new Promise((resolve, reject) => {
                const results = [];

                return client
                    .stream(query, params, options)
                    .on('readable', function() {
                        // 'readable' is emitted as soon a row is received and parsed
                        let row;

                        while ((row = this.read())) {
                            results.push(row);
                        }
                    })
                    .on('end', function() {
                        // Stream ended, there aren't any more rows
                        return resolve(results);
                    })
                    .on('error', function(err) {
                        return reject(err);
                    });
            }),