我从cassandra读取流时遇到了一些问题(我甚至不知道我想要实现的是什么)。所以在 cassandra-driver git存储库页面上有一个如何使用流的示例。我已经尝试过它并且有效。
但是我正在尝试使用带有nodejs 5的ES6提案中所谓的类。我想将模型定义为一个类,并且在我使用流的一个方法中(我从cassandra获取数据)。 问题出在可读状态,其中你在回调函数中有this.read(),现在当在类中调用它时,它变成了一个类范围,所以它总是未定义的。我已尝试使用 cassandra-driver 模块中的ResultStream扩展我的课程,但没有运气,也许我没有正确地调用它。我已尝试使用数据状态(不同的类和方法作为回调)并且它正在工作,因为数据状态有一个参数作为块传递。
所以问题是,如何在类方法中封装此流调用,以便可读取可读状态?
我想要实现的示例代码:
class Foobar {
constructor(client) {
this.client = client;
this.collection = [];
this.error;
}
getByProductName(query, params) {
this.client.stream(query, params, {prepare: true})
.on('readable', () => {
var row;
while(row = this.read()) { // Problem with this scope
this.collection.push(row);
}
})
.on('error', err => {
if(err) {
this.error = err;
}
})
.on('end', () => {
console.log('end');
});
}
}
感谢您的任何建议。
答案 0 :(得分:3)
您可以在闭包中捕获stream
实例:
class Foobar {
constructor(client) {
this.client = client;
this.collection = [];
this.error;
}
getByProductName(query, params) {
const stream = this.client.stream(query, params, { prepare: true })
.on('readable', () => {
var row;
while(row = stream.read()) { // <- use stream instance
this.collection.push(row);
}
})
.on('error', err => {
if(err) {
this.error = err;
}
})
.on('end', () => {
console.log('end');
});
}
}