wait-for-event-promise
A simple module that exposes a function used to wait for specific events from an emitter.
Installation
npm install wait-for-event-promise
Usage
waitForEvent(emitter: EventEmitter, eventName: String [, filter: Function, options: Object ])
A minimal example:
const waitForEvent = ;const EventEmitter = { // create event emitter const emitter = ; // create a promise for wait for a 'hello' event const helloPromise = ; // emit a hello event emitter; // promise will resolve with the data that was emit const event = await helloPromise; // { message: 'world' } console; // outputs: 'world'};
A function can be passed into to filter out events that you don't care about.
const emitter = ; const helloPromise = ; emitter;// we don't care about bob, so helloPromise has not resolved yet emitter;// now helloPromise has resolved const event = await helloPromise;console; // outputs: 'world'
Alternatively, a filter can be provided as part of the options
object.
;
A timeout can also be used to ensure you don't indefinitely wait on an event. If the emitter does not emit the proper event before the timeout, the promise will reject.
const emitter = ; // wait for 1000 ms before rejectingconst helloPromise = ; try await helloPromise; catch err // after 1000 ms has passed console; // err.message === "Timed out waiting for event"
A timeout can also be used with a filter function.
; // alternatively, you can use supply the filter function in the options;
A logging function can be passed in to get more information about what the module is doing.
const helloPromise = ; emitter;emitter;emitter;emitter;
In your logs, you will see the following output:
Waiting for event: hello
Filtering for event: hello
Filtering for event: hello
Filtering for event: hello
Got matching event: hello