节点将侦听器与Javascript类组合在一起

时间:2018-03-08 12:40:47

标签: javascript node.js asynchronous

我正在寻找一个好的模式,它结合了Javascript类,事件监听器和异步编程。

我正在尝试为我的项目编写一个共享库来处理与Kafka服务器的连接。 kafka节点库要求您连接然后为“已连接”事件设置侦听器。我想掩盖其他需要向kafka发送消息的库的复杂性。

以下代码基本上有效,但我觉得它很复杂(在事件监听器中解析Promise)并且必须有更好的方法

class KafkaProducer {

   constructor(id) {

      this.connected_mode = process.env.KAFKA_CONNECT !== 'false';
      this.hostname = process.env.NODE_ENV === 'development' ? '192.168.99.100:2181' : 'service-kafka:2181';
      this.id = id ? id : 'no_name_specified';

      log.info(`KafkaProducer: hostname: ${this.hostname} id: ${this.id}`);

      if (this.connected_mode === false) {
        log.info('KafkaProducer: Running in disconnected mode');
        this.ready = true;
        return;
      }

      this.client = new Client(this.hostname, this.id, {
         sessionTimeout: 300,
         spinDelay: 100,
         retries: 2
      });
      this.ready = false;
      this.connected = false;
      this.producer = false;
      this.metrics = {};
   }

   initialize() {

      let that = this;

      log.silly(`KafkaProducer.initialize: Initializing with connected_mode=${this.connected_mode}`);

      return new Promise((resolve, reject) => {

         if (that.connected_mode === false) {
            log.silly('KafkaProducer.initialize: Returning early in disconnected mode');
            return resolve();
         }

         if (that.ready && that.producer) {
            log.silly('KafkaProducer.initialize: Returning early as both ready and producer are set');
            return resolve();
         }

         log.silly(`KafkaProducer.initialize: Creating Producer with client details connectionString=${that.client.connectionString}`)
         that.producer = new Producer(that.client, {requireAcks: 1});

         that.producer.on('ready', () => {
            log.info('KafkaProducer: Producer is ready');
            that.ready = true;
            that.connected = true;
            return resolve();
         });

         that.producer.on('error', (err) => {
            log.error(`KafkaProducer: ${err}`);
         });
      });
   }

需要发送Kafka消息的其他代码可以导入此类,检查ready属性并在必要时进行初始化

KafkaProducer.initialize().then(() => {
    KafkaProducer.sendMessage('foo');
});

但是从事件监听器中解析Promise就像是糟糕的代码。还有更好的方法吗?

编辑:我错误地写了“返回”承诺而不是“解决”......纠正了问题

0 个答案:

没有答案