@themaxdavitt/s-event

Synchronously wait for an event - please invoke responsibly

Usage no npm install needed!

<script type="module">
  import themaxdavittSEvent from 'https://cdn.skypack.dev/@themaxdavitt/s-event';
</script>

README

@themaxdavitt/s-event

NPM link Package license standard-readme compliant

Synchronously wait for an event - please invoke responsibly

Background

Despite being almost irredeemably unidiomatic, sometimes being able to synchronously listen for an event is convenient. Please don't do this unless you're sure you can't use promises. You probably can.

Install

npm install s-event

Support for multiple "typed emitter" packages is included among separate modules:

These are included as optional dependencies for this package.

Additionally, @themaxdavitt/s-event/lib/util's default export is on(emitter: any, event: any) => any - see the doc comment for the assumptions it makes.

Usage

The default exported function from each module takes 2 parameters:

  1. The emitter to temporarily attach a listener for the event on
  2. The event to listen for

It will synchronously listen for the event on the emitter and, when it's emitted, will return a tuple (internally an array) of that first event's arguments.

An example using the Node.js EventEmitter:

import {strict as assert} from 'assert';
import {EventEmitter} from 'events';
import onEventEmitter from '@themaxdavitt/s-event';

const ee = new EventEmitter();

setTimeout(() => ee.emit('e', 1, 2), 1000);

assert(onEventEmitter(ee, 'e').length === 2);

Additional examples are in src/test.ts.

NOTE: Support for type-safe Symbol events not using the standard EventEmitter is pending on this issue.

Contributing

Feel free to submit issues if you have any, and pull requests if you want to implement something!

License

MIT License. Copyright © 2020 Max Davitt. See LICENSE.