Skip to content
jshacks.dev
Async

Event Emitters vs Promises vs Observables

Compare event emitters, promises and observables on how many values they carry, whether they are lazy, how they cancel and which one to use for each job.

6 min read
Summarize in AI
Flat illustration of jobs on a conveyor heading to a rack of workers, with the JavaScript, RabbitMQ and Apache Kafka logos.

Three abstractions model "something will happen later" in JavaScript, and they differ along two axes that decide which one fits. How many values can arrive: one, or many? And who is in charge: does the producer push whenever it likes, or does nothing happen until a consumer asks? A promise carries exactly one value and runs eagerly. An event emitter carries any number of values over time and runs whenever its source emits. An observable carries any number of values, starts only when subscribed and gives each subscriber its own run. Picking the wrong one causes the familiar bugs: a promise used for something that repeats, an emitter listener that never gets removed, an observable subscribed to twice that makes two requests. This post compares them on the same task on Node.js 24, using the EventEmitter from node:events, native promises and the RxJS 7 Observable for the third, then gives a table for choosing.

The shapes side by side

PromiseEvent emitterObservable
ValuesExactly one, or an errorZero or more, over timeZero or more, then complete or error
StartsImmediately, on creationWhenever the source emitsOn subscribe, once per subscriber
Multiple consumersShare one resultShare each emissionEach subscriber gets its own run (cold)
CancelNot built in; use AbortSignalremoveListenerunsubscribe()
ErrorsOne rejectionAn error event by conventionerror channel, ends the stream
Built inYesNode.js, and EventTarget in browsersNo; RxJS or the TC39 proposal

The first row is the one to settle on before looking at anything else. If the result is a single value, a promise is almost always the right model, and the other two add machinery you do not need.

One value: a promise

JavaScript
function loadUser(id) {
  return new Promise((resolve) => {
    setTimeout(() => resolve({ id, name: "Ada" }), 10);
  });
}

const user = await loadUser(1);
console.log(user);

const again = await loadUser(1);
console.log(again === user);
Text
{ id: 1, name: 'Ada' }
false

Each call creates a new promise and starts new work. Awaiting the same promise twice would give the same value, but calling the function twice does the work twice. A promise settles once, and every handler attached to it, before or after, receives that result.

Many values, pushed: an event emitter

An emitter has no concept of completion or of "the current value". Things happen, and whoever is listening at that moment is told.

JavaScript
import { EventEmitter } from "node:events";

const ticker = new EventEmitter();

ticker.on("tick", (n) => console.log("listener A got", n));

ticker.emit("tick", 1);

ticker.on("tick", (n) => console.log("listener B got", n));

ticker.emit("tick", 2);
Text
listener A got 1
listener A got 2
listener B got 2

Listener B joined late and never saw the first tick. The emitter does not remember. That is right for things like clicks and incoming messages, where the past is irrelevant, and wrong when a late subscriber needs history. Listeners are synchronous: emit calls each one in order before it returns, and a listener that throws interrupts the rest.

An emitter that you forget to unsubscribe from keeps the listener, and anything it references, alive.

JavaScript
const emitter = new EventEmitter();

function handler() {}
emitter.on("data", handler);

console.log("listeners:", emitter.listenerCount("data"));

emitter.off("data", handler);

console.log("after off:", emitter.listenerCount("data"));
Text
listeners: 1
after off: 0

Node.js prints a warning when more than ten listeners attach to one event, because that number usually signals a leak.

Many values, pulled by subscription: an observable

An observable is a function that describes how to produce values. Nothing runs until someone subscribes, and each subscription runs the function afresh.

JavaScript
import { Observable } from "rxjs";

const numbers = new Observable((subscriber) => {
  console.log("producer started");
  subscriber.next(1);
  subscriber.next(2);
  subscriber.complete();
});

console.log("created, nothing has run");

numbers.subscribe({
  next: (value) => console.log("A:", value),
  complete: () => console.log("A: complete"),
});

numbers.subscribe((value) => console.log("B:", value));
Text
created, nothing has run
producer started
A: 1
A: 2
A: complete
producer started
B: 1
B: 2

The producer ran twice, once per subscriber. That is what "cold" means. If the producer is an HTTP request, two subscribers mean two requests, which surprises people coming from promises. Operators such as share() and shareReplay() turn a cold observable into a shared, "hot" one, so subscribers join a single run.

Observables also bring a vocabulary for transforming sequences. Operators like map, filter and debounceTime compose into pipelines, and unsubscribe() stops the production and runs any cleanup the producer returned.

JavaScript
import { Observable } from "rxjs";

const ticks = new Observable((subscriber) => {
  let n = 0;
  const id = setInterval(() => subscriber.next(++n), 10);
  return () => {
    clearInterval(id);
    console.log("cleaned up");
  };
});

const subscription = ticks.subscribe((n) => console.log("tick", n));

setTimeout(() => subscription.unsubscribe(), 35);
Text
tick 1
tick 2
tick 3
cleaned up

The teardown function returned from the producer is what makes cancellation reliable: unsubscribing clears the interval. The tick count at 35 ms is three at typical timer accuracy.

The same task three ways

The task: do something with the first message that arrives on a channel.

JavaScript
import { EventEmitter, once } from "node:events";

const channel = new EventEmitter();

setTimeout(() => channel.emit("message", "hello"), 10);

// promise style, from an emitter
const [message] = await once(channel, "message");
console.log("promise:", message);
Text
promise: hello

events.once converts the next emission into a promise, the bridge between the first two models. The reverse bridge is Promise.withResolvers or a promise constructor that calls resolve from a listener. For observables, firstValueFrom(observable) and lastValueFrom(observable) return promises, and fromEvent(emitter, "message") creates an observable from an emitter. Converting at the edges lets each part of a program use the model that fits it.

Async iteration is a fourth option for many values with pull control. events.on(emitter, "message") yields every emission through for await, with the consumer in charge of pace.

JavaScript
const controller = new AbortController();

setTimeout(() => channel.emit("message", "one"), 5);
setTimeout(() => channel.emit("message", "two"), 10);
setTimeout(() => controller.abort(), 20);

try {
  for await (const [text] of on(channel, "message", { signal: controller.signal })) {
    console.log("iterated:", text);
  }
} catch (error) {
  console.log(error.name);
}
Text
iterated: one
iterated: two
AbortError

This needs import { on } from "node:events" alongside the earlier imports. The loop sees both messages and ends when the signal aborts.

When each one wins

Use a promise for one-time results: a request, a file read, a database query, a one-shot initialization. It is native, integrates with async/await and handles errors with try/catch. Do not use it for things that happen repeatedly. A promise that resolves on the first click ignores the second.

Use an event emitter for notifications with many independent listeners and no completion: UI events, server events, a plugin hook system. It is simple and built in. Be careful with listener cleanup, and with the error event, which throws if it is emitted with no listener.

Use an observable when you need to transform, combine or time sequences: autocomplete with debounce and cancellation of stale requests, merging several streams, retries with back off, or a UI model in a framework that already uses RxJS. Its operators are the benefit, and its learning curve and bundle size are the price. For simple cases, an async generator or an emitter is lighter.

Cancellation and errors, compared

Promises cannot be cancelled by the consumer, so the producer must accept a signal. Emitters cancel by removing the listener, and the producer keeps running. Observables cancel by unsubscribing, and a well-written producer stops. On errors, a promise rejects once, an emitter's error event is only a convention and an observable's error ends the stream for that subscriber, which differs from an emitter that keeps working after an error event.

A rule of thumb for mixed systems

Real programs use all three, and the cleanest designs convert at boundaries and keep each layer in one model. Low-level code that talks to a socket or a hardware device is naturally an emitter. Application services that perform operations are naturally promise-based. Code that coordinates user input over time may be easiest as observables. When you must cross a boundary, do it once and name the conversion, such as a function called nextMessage that wraps once, so the rest of the code does not need to know where the value came from.

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.