Skip to content
jshacks.dev
Async

How to Write a Promise-Based Event Bus in JavaScript

Write a promise-based event bus in JavaScript: subscribe, publish and await all handlers, isolate errors, add once and waitFor, and unsubscribe cleanly.

7 min read
Summarize in AI
Flat illustration of an editor window full of code, with the JavaScript, npm and Vite logos.

An event bus lets parts of a program talk without knowing each other. A publisher announces that something happened, and any number of subscribers react. The classic version is synchronous: emit calls each handler and returns. That breaks down once handlers do async work. The publisher cannot tell when the work is finished, an error in a handler becomes an unhandled rejection and ordering between handlers becomes a guess. A promise-based event bus fixes this by making publish return a promise that settles when the handlers have. This post writes one in plain JavaScript for Node.js 24 and browsers, step by step: subscribe and unsubscribe, publish that awaits every handler, error handling that does not let one handler break the others, a once method, and a waitFor method that turns an event into a promise. It builds on wrapping events with Promise.withResolvers and cleaning up listeners with AbortSignal.

The smallest bus

A bus is a map from event name to a set of handlers. subscribe adds a handler and returns a function that removes it. publish calls the handlers with the payload.

bus.jsJavaScript
export class EventBus {
  #handlers = new Map();

  subscribe(name, handler, { signal } = {}) {
    if (!this.#handlers.has(name)) this.#handlers.set(name, new Set());
    const set = this.#handlers.get(name);
    set.add(handler);

    const unsubscribe = () => {
      set.delete(handler);
      if (set.size === 0) this.#handlers.delete(name);
    };
    signal?.addEventListener("abort", unsubscribe, { once: true });
    return unsubscribe;
  }

  async publish(name, payload) {
    const handlers = [...(this.#handlers.get(name) ?? [])];
    const results = await Promise.allSettled(handlers.map((handler) => handler(payload)));
    const errors = results.filter((r) => r.status === "rejected").map((r) => r.reason);
    if (errors.length > 0) throw new AggregateError(errors, `${errors.length} handler(s) failed for "${name}"`);
  }
}

const bus = new EventBus();
bus.subscribe("user.created", async (user) => {
  await new Promise((resolve) => setTimeout(resolve, 10));
  console.log("welcome email for", user.name);
});
bus.subscribe("user.created", (user) => console.log("audit log for", user.name));

await bus.publish("user.created", { name: "Ada" });
console.log("all handlers finished");
Text
audit log for Ada
welcome email for Ada
all handlers finished

The synchronous handler printed first because the async one waited 10 milliseconds. publish returned only after both had finished, which is the guarantee a plain emitter cannot give. Copying the handler set before calling lets a handler subscribe or unsubscribe during delivery without changing the current round.

Run handlers in parallel or in series

The version above starts every handler at once with Promise.allSettled. That is fast, and it means handlers must not depend on each other's order. Some buses run handlers one after another in subscription order, which makes them slower and gives each handler a defined place. Offer both and let the caller pick, because the right answer depends on the event.

series.jsJavaScript
export async function publishInSeries(handlers, payload) {
  const errors = [];
  for (const handler of handlers) {
    try {
      await handler(payload);
    } catch (error) {
      errors.push(error);
    }
  }
  if (errors.length > 0) throw new AggregateError(errors, `${errors.length} handler(s) failed`);
}

const order = [];
await publishInSeries(
  [
    async () => {
      await new Promise((resolve) => setTimeout(resolve, 20));
      order.push("slow first");
    },
    async () => order.push("fast second"),
  ],
  null
);
console.log(order);
Text
[ 'slow first', 'fast second' ]

In series, the slow handler finishes before the fast one starts. In parallel, the order would be reversed. Choose series for steps that build on one another, such as validate, then save, then notify, and parallel for independent reactions.

Isolate errors

A failing handler must not stop the others. With Promise.allSettled, every handler runs to completion, and the bus gathers the failures into one AggregateError. Whether the publisher should see that error is a design choice. If the publisher needs to know that all reactions succeeded, rethrow as above. If it is fire-and-forget, catch and log inside the bus instead, so a broken subscriber cannot break an unrelated publisher.

errors.jsJavaScript
import { EventBus } from "./bus.js";

const bus = new EventBus();
bus.subscribe("job.done", async () => {
  throw new Error("webhook failed");
});
bus.subscribe("job.done", async () => console.log("metrics recorded"));

try {
  await bus.publish("job.done", {});
} catch (error) {
  console.log(error.message);
  console.log(error.errors.map((e) => e.message));
}
Text
metrics recorded
1 handler(s) failed for "job.done"
[ 'webhook failed' ]

The healthy handler ran and recorded its metrics even though its neighbor failed. The publisher then learned about the failure through the aggregate, with the original errors preserved.

once and waitFor

A handler that should run for the next event only is common, and it composes from subscribe. A waitFor method that returns a promise for the next payload is even more useful, because it lets code await an event.

wait.jsJavaScript
import { EventBus } from "./bus.js";

EventBus.prototype.once = function once(name, handler) {
  const unsubscribe = this.subscribe(name, async (payload) => {
    unsubscribe();
    await handler(payload);
  });
  return unsubscribe;
};

EventBus.prototype.waitFor = function waitFor(name, { signal } = {}) {
  const { promise, resolve, reject } = Promise.withResolvers();
  const unsubscribe = this.subscribe(name, resolve, { signal });
  signal?.addEventListener("abort", () => reject(signal.reason), { once: true });
  promise.finally(unsubscribe).catch(() => {});
  return promise;
};

const bus = new EventBus();
setTimeout(() => bus.publish("ready", { port: 3000 }), 10);

const { port } = await bus.waitFor("ready");
console.log("server ready on", port);
Text
server ready on 3000

waitFor creates a deferred, subscribes with its resolve and removes the subscription when the promise settles, so waiting does not leak a handler. Passing a signal gives a timeout or a cancel path, as in bus.waitFor("ready", { signal: AbortSignal.timeout(5000) }).

Typed events

In TypeScript, give the bus a map from event names to payload types, so publish("user.created", { name: "Ada" }) is checked and a handler receives a typed payload. In JavaScript, the same discipline comes from a short list of event names exported as constants, and a doc comment on each one that states the payload shape. Without that, a bus drifts into a place where nobody knows which events exist or what they carry, which is the main long-term cost of this pattern.

What an event bus is not

A bus in memory connects code in one process. It does not survive a restart, it does not reach other servers and it does not retry failed handlers. If an event matters, such as "payment received", and losing it is not acceptable, publish it to a durable queue or write it to the database in the same transaction, and let a worker deliver it. Use the in-process bus for reactions that are allowed to be lost, such as updating a cache, refreshing a view or writing a log line.

Ordering and re-entrancy

Two details decide whether a bus behaves predictably under load. The first is ordering across events. If handler A publishes event two while handling event one, does event two run to completion before event one's other handlers continue, or after? With the parallel version above, handlers of event one run concurrently, so A's nested publish interleaves with them. That is fine when handlers are independent, and it is a source of confusing bugs when they are not. If you need a strict order, queue publishes: keep a promise chain, as in the serialized function pattern, so each publish starts only after the previous one finished.

The second is re-entrancy, where a handler publishes the same event it is handling. Without a guard, that is an infinite loop that never yields an error, only a growing call stack or a never-ending chain of promises. Add a depth counter to the bus and throw when it passes a small limit, such as ten, with an error that names the event. A thrown error on day one is far easier to debug than a hung process on day ninety.

Observability

A bus makes control flow invisible: reading the publisher tells you nothing about what happens next. Make it visible. Add a debug hook, called with the event name, the number of handlers and the duration of the publish, and log it at a low level. Count handler failures per event and expose the counts as metrics. When someone asks what runs when a user is created, a listing of the subscribers by event name, produced from the bus itself, is a much better answer than a search through the codebase. A listeners(name) method that returns handler names takes a few lines to add, and it works best when handlers are named functions, not anonymous arrows.

Testing a bus

The bus is easy to test because it has no timers of its own. Subscribe two handlers with deferred promises, publish, assert that neither has finished, resolve both and assert that the publish promise settles afterward. Test that a throwing handler does not prevent the others from running and that the aggregate holds its error. Test unsubscribe by calling the returned function and publishing again, and test the abort signal path the same way. Finally, test waitFor with a timeout signal, and assert that the subscription count goes back to zero after the timeout, since a leaked subscription there would accumulate in a long-running process.

When to choose something else

If the same few components always talk to each other, a direct function call is clearer than an event, because the call shows up in the code, in the type checker and in the stack trace. Use a bus when the publisher should not know who listens, as with plugins, cross-cutting concerns such as audit logs and loosely coupled modules. Reach for a library such as mitt or Node's EventEmitter when you want something tiny and synchronous, and write your own, as here, when async handlers and their errors are the point.

Taggedbeginner
Share

Keep reading

Flat illustration of an editor window full of code, with the Google Chrome, JavaScript and npm logos.
Browser

script Tags: async, defer and type=module

Compare classic, async, defer and module script tags: when each downloads, when each runs, how order is kept and which one to pick for each kind of script.

6 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.