【问题标题】:How to use Node.js promises for a function (CassandraDB driver when executing query)如何对函数使用 Node.js 承诺(执行查询时的 CassandraDB 驱动程序)
【发布时间】:2018-11-05 21:10:57
【问题描述】:

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

查询完成后,我想返回我的数组,但它总是返回“未定义”,我猜是因为获取查询需要很长时间,所以 Javascript 在对象被填充之前继续返回语句。

对于不熟悉这个驱动的人来说: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.js asynchronous cassandra promise datastax-enterprise


    【解决方案1】:

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

    您自己缓冲所有行然后返回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/

    【讨论】:

      【解决方案2】:

      为了补充答案,我能够让 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);
                          });
                  }),
      

      【讨论】:

        猜你喜欢
        • 2021-06-09
        • 1970-01-01
        • 1970-01-01
        • 2016-08-25
        • 2021-01-04
        • 1970-01-01
        • 2017-01-13
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多