AsyncEventEmitter
by Nicholas C. Zakas
If you find this useful, please consider supporting my work with a donation.
Description
A utility for emitting events and responding with asynchronous functions.
Usage
Node.js
Install using npm or yarn:
npm install @humanwhocodes/async-event-emitter
# or
yarn add @humanwhocodes/async-event-emitter
Import into your Node.js project:
const { AsyncEventEmitter } = require("@humanwhocodes/async-event-emitter");
import { AsyncEventEmitter } from "@humanwhocodes/async-event-emitter";
Deno
Import into your Deno project:
import { AsyncEventEmitter } from "https://cdn.skypack.dev/@humanwhocodes/async-event-emitter?dts";
Bun
Install using this command:
bun add @humanwhocodes/async-event-emitter
Import into your Bun project:
import { AsyncEventEmitter } from "@humanwhocodes/async-event-emitter";
Browser
It's recommended to import the minified version to save bandwidth:
import { AsyncEventEmitter } from "https://cdn.skypack.dev/@humanwhocodes/async-event-emitter?min";
However, you can also import the unminified version for debugging purposes:
import { AsyncEventEmitter } from "https://cdn.skypack.dev/@humanwhocodes/async-event-emitter";
API
After importing, create a new instance of AsyncEventEmitter to start emitting events:
const emitter = new AsyncEventEmitter();
emitter.on("foo", async () => "hello!");
emitter.on("foo", () => "goodbye!");
const results = await emitter.emit("foo");
console.log(results);
emitter.on("exclaim", suffix => "hello" + suffix);
emitter.on("exclaim", suffix => "goodbye" + suffix);
const results = await emitter.emit("exclaim", "!");
console.log(results);
const count = emitter.listenerCount("exclaim");
console.log(count);
const handler = () => {};
emitter.on("bar", handler);
emitter.off("bar", handler);
const results = await emitter.emit("bar");
console.log(results);
Developer Setup
- Fork the repository
- Clone your fork
- Run
npm install to setup dependencies
- Run
npm test to run tests
License
Apache 2.0