emit-then

2.0.0 • Public • Published

emit-then Build Status NPM version

EventEmitter.prototype.emit that wraps event calls in a promise.

Installation

$ npm install emit-then

Setup

Add emitThen to your emitter prototype(s):

http.server.emitThen = require('emit-then');

Or register emitThen on EventEmitter.prototype to make it available on all emitters:

require('emit-then').register();

Usage

Traditional event handlers behave as usual:

emitter.on('event', function (argument) {
  console.log('hi there!');
});
emitter.emitThen('event', argument).then(function () {
  // logged: hi there!
});

Handlers can return promises:

emitter
  .on('event', function () {
    return promise.then(function () {
      console.log('hi there!');
    });
  })
  .emitThen('event')
  .then(function () {
    // logged: hi there!
  });

Just like calling emit, the return value or resolution of the promise is unused.

If a handler returns a rejected promise, emitThen is immediately rejected with the error:

emitter
  .on('event', function () {
    return Promise.reject(new Error('rejected!'));
  })
  .emitThen('event')
  .catch(function (err) {
    // err.message => 'rejected!'
  });

You can also reject emitThen by throwing an error from a handler:

emitter
  .on('event', function () {
    throw new Error('rejected!');
  })
  .emitThen('event')
  .catch(function (err) {
    // err.message => 'rejected!'
  });

Package Sidebar

Install

npm i emit-then

Weekly Downloads

74

Version

2.0.0

License

MIT

Last publish

Collaborators

  • bendrucker