You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

49 lines
1.8 KiB
Markdown

5 months ago
# promisify-event
Gives you a Promise for a specified event on an EventEmitter that is only expected to happen once. Also automatically wires up the `error` event.
Works with anything that implements the Node.js EventEmitter API (which is pretty much everything other than the DOM).
Note that this is __not__ suitable for events that are expected to be emitted multiple times, because Promises can only represent one-off successes and failures; if you need a series of values over time, you may want to look at [Promistreams](https://promistream.cryto.net/) and particularly [`@promistream/from-event-emitter`](https://www.npmjs.com/package/@promistream/from-event-emitter) instead.
## Example
Also included in the package in runnable form, as `example.js`.
```js
"use strict";
const createEventEmitter = require("create-event-emitter");
const promisifyEvent = require("./");
// Demonstrated with a dummy event emitter, but it works with any EventEmitter
let emitter = createEventEmitter();
(async function () {
console.log("waiting...");
await promisifyEvent(emitter, "test");
console.log("emitted!");
})();
console.log("emitting...");
emitter.emit("test");
/* Output:
waiting...
emitting...
emitted!
*/
```
## API
### promisifyEvent(emitter, eventName)
- __emitter:__ Any `EventEmitter`. This is the emitter that you want to listen for the event on.
- __eventName:__ The event name to watch for.
__Returns:__ A Promise that resolves when the event occurs, or rejects (with the error in question) if an `error` event occurs first.
Note that when the Promise resolves successfully, it resolves with an *array of* arguments passed to the event callback, as event handlers may receive any number of arguments. It's recommended to use array destructuring syntax to unpack it into variables.