2015-09-25 59 views
2

我正在尝试创建一个具有未来的功能。在此功能中,它将等待EndError事件。如果没有数据写入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(); 
} 

我遇到了一些问题。

  • 当未来的回报,该事件侦听器仍结合
  • 未来可以因为超时

这是如何通常与期货的处理返回多次?有没有办法清理这些事件?

回答

2

首先我建议你做this.once而不是this.on,这样你只会触发事件处理程序一次。 没有必要多次触发它。

此外,我建议你做

var self = this; 
done = function (err, result) { 
    //remove all listeners 
    self.removeListener('Error', handler); 
    //.... and so on.... 

    future.resolver()(err, result);//call actual done 
} 

这将防止被调用一次以上的完成和删除事件侦听器。

+0

啊,'一次'是非常有帮助的!谢谢你好先生 – corvid

+0

曾经会阻止同一个事件的多次处理,但是如果触发不同的事件,你仍然会得到多个调用,所以你也必须按照我原来写的那样做事件监听器清理。 – sagie

+0

我唯一的其他问题是处理超时。我无法找到指定“仅从一系列期货中返回一个未来”的API API中的任何内容(以先到者为准) – corvid

相关问题