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.

1.8 KiB

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 and particularly @promistream/from-event-emitter instead.

Example

Also included in the package in runnable form, as example.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.