event-2-promise
v1.0.1
Published
This package is used to turn events into promises.
Downloads
4
Readme
Event To Promise
This package is used to turn events into promises.
API
EventToPromise(emitter, [throwEvents])
- Constructor.ep#promise(event, [timeout])
- Return a promise for event.ep#getEmitter(event, [timeout])
- Get emitter.
emitter
- Event emitter.
throwEvents
- promise method will throw those events emitted arguments if they are emitted.
timeout
- Timeout in miliseconds.
Error Handling: promise method will throw only errors
which can be an instance of EventToPromise.errors.Timeout or an object {event:emittedArgs, ...}
containing errors from specified throw events in constructor.
Installation
npm i -s event-2-promise
Example
const EventToPromise = require('event-2-promise');
const net = require('net');
(async () => {
const socket = new net.Socket();
const socketEP = new EventToPromise(socket, ['error', 'close']);
try {
socket.connect(80, '123.123.123.123');
const emittedArgsConnect = await socketEP.promise('connect', 2000);
const emittedArgsData = await socketEP.promise('data', 5000);
} catch (err) {
socket.destroy();
if (err instanceof EventToPromise.errors.Timeout) {
if (err.getEvent() === 'connect') {
console.log('connect event timeout');
} else if (err.getEvent() === 'data') {
console.log('data event timeout');
}
} else {
// err is a json object containing:
// event name as a key {String} and emitted arguments as value {Array}
// in this case the key can only be 'error' or 'close' because those are the events
// which were specified as throw events
console.log(err);
}
}
})();