corvid
corvid

Reputation: 11197

How to create future with timeout and listeners

I am trying to create a function with a future. In this function, it will wait for an End or Error event. If no data is written for x seconds, it will return an error. Here is what I have written.

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();
}

I'm running across a few problems.

How is this usually handled with futures? Is there some way to clean up these events?

Upvotes: 2

Views: 577

Answers (1)

sagie
sagie

Reputation: 1777

First I suggest you do this.once and not this.on so you will trigger the event handler only once. There is no need to trigger it more than once.

Also I suggest you do

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

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

That would prevent the done from being called more than once and remove the event listeners.

Upvotes: 2

Related Questions