【发布时间】:2015-12-23 10:39:49
【问题描述】:
我正在尝试创建一个具有未来的功能。在此函数中,它将等待End 或Error 事件。如果 x 秒内没有写入数据,则会返回错误。这是我写的。
Cylon.execute = function (subroutine, timeout=60000) {
let future = new Future();
let done = future.resolver();
let timeoutId = Meteor.setTimeout(function () {
done(new Meteor.Error('CylonTimeout'));
});
this._messages.on('data', () => {
timeoutId = Meteor.setTimeout(function () {
done(new Meteor.Error('CylonTimeout'));
});
});
this.on('End', () => {
Meteor.clearTimeout(timeoutId);
done(null, subroutine);
})
this.on('Error', (err) => {
Meteor.clearTimeout(timeoutId)
done(err, null)
});
this._commands.write(`Execute #${subroutine}\r`, 'utf8');
return future.wait();
}
我遇到了一些问题。
- future 返回时,仍绑定事件监听器
- future 会因为超时而返回多次
期货通常如何处理?有什么方法可以清理这些事件吗?
【问题讨论】:
标签: javascript node.js events asynchronous meteor