https://github.com/bendrucker/emit-then
EventEmitter.emit that wraps event calls in a promise
https://github.com/bendrucker/emit-then
Last synced: over 1 year ago
JSON representation
EventEmitter.emit that wraps event calls in a promise
- Host: GitHub
- URL: https://github.com/bendrucker/emit-then
- Owner: bendrucker
- License: mit
- Created: 2014-03-20T19:11:58.000Z (over 12 years ago)
- Default Branch: master
- Last Pushed: 2019-08-06T11:45:44.000Z (almost 7 years ago)
- Last Synced: 2025-04-10T08:13:59.760Z (over 1 year ago)
- Language: JavaScript
- Size: 15.6 KB
- Stars: 6
- Watchers: 4
- Forks: 1
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
emit-then [](https://travis-ci.org/bendrucker/emit-then) [](http://badge.fury.io/js/emit-then) [](https://greenkeeper.io/)
========
`EventEmitter.prototype.emit` that wraps event calls in a promise.
## Installation
```bash
$ npm install emit-then
```
## Setup
Add `emitThen` to your emitter prototype(s):
```js
http.server.emitThen = require('emit-then');
```
Or register `emitThen` on `EventEmitter.prototype` to make it available on all emitters:
```js
require('emit-then').register();
```
## Usage
Traditional event handlers behave as usual:
```js
emitter.on('event', function (argument) {
console.log('hi there!');
});
emitter.emitThen('event', argument).then(function () {
// logged: hi there!
});
```
Handlers can return promises:
```js
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:
```js
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:
```js
emitter
.on('event', function () {
throw new Error('rejected!');
})
.emitThen('event')
.catch(function (err) {
// err.message => 'rejected!'
});
```