events once and events on in Node.js 24 Explained
Learn how events.once awaits a single event and events.on iterates many events as an async iterator in Node.js 24, with cancellation, errors and buffering.

An EventEmitter speaks callbacks, and most modern Node.js code speaks await. The node:events module closes that gap with two static functions: events.once(emitter, name) returns a promise for the next occurrence of an event, and events.on(emitter, name) returns an async iterator over every occurrence. Both are small, both handle the error event for you, and both have behavior in the corners that is worth knowing before you build on them. This post shows each with exact output for Node.js 24, covers cancellation with AbortSignal, explains what happens to events that arrive while your loop body is busy and lists the cases where a plain listener is still the better choice.
events.once: wait for the next event
import { EventEmitter, once } from "node:events";
const emitter = new EventEmitter();
setTimeout(() => emitter.emit("ready", "db", 5432), 20);
const args = await once(emitter, "ready");
console.log(args);[ 'db', 5432 ]The promise resolves with an array of all the arguments passed to emit, not the first argument alone, because an event can carry several. Destructure when you know the shape: const [name, port] = await once(emitter, "ready").
The listener is removed after the first event, so there is nothing to clean up. A second emit("ready") is ignored by this promise, though other listeners still see it.
The error event rejects the promise
If the emitter emits error while you wait for another event, the promise rejects with that error, and the listeners are removed.
import { EventEmitter, once } from "node:events";
const emitter = new EventEmitter();
setTimeout(() => emitter.emit("error", new Error("connection lost")), 10);
try {
await once(emitter, "ready");
} catch (error) {
console.log("failed:", error.message);
}failed: connection lostThis is the main advantage over new Promise((resolve) => emitter.once("ready", resolve)), which leaves the error unhandled, and an error event with no listener throws and can crash the process. When you wait for "error" itself, once does not apply this rule, and resolves with the error as a normal event.
Waiting for either of two events
once waits for one name. To wait for the first of several, race them and cancel the loser.
import { EventEmitter, once } from "node:events";
const emitter = new EventEmitter();
const stop = new AbortController();
setTimeout(() => emitter.emit("close"), 10);
const winner = await Promise.race([
once(emitter, "data", { signal: stop.signal }).then(() => "data"),
once(emitter, "close", { signal: stop.signal }).then(() => "close"),
]);
stop.abort();
console.log(winner);closeAborting the signal removes the leftover data listener. The aborted once rejects with an AbortError, and Promise.race already subscribed to that promise, so it does not produce an unhandled rejection.
Cancellation
Pass a signal and once rejects with an AbortError when it aborts, removing its listener.
import { EventEmitter, once } from "node:events";
const emitter = new EventEmitter();
const controller = new AbortController();
setTimeout(() => controller.abort(), 20);
try {
await once(emitter, "never", { signal: controller.signal });
} catch (error) {
console.log(error.name);
}AbortErrorWithout a signal, a once for an event that never comes keeps a promise and a listener alive for as long as the emitter lives, which is a slow leak in long-running servers.
events.on: an async iterator over events
on(emitter, name) returns an async iterator. Each iteration yields the arguments array of one emit.
import { EventEmitter, on } from "node:events";
const emitter = new EventEmitter();
setTimeout(() => emitter.emit("message", "one"), 10);
setTimeout(() => emitter.emit("message", "two"), 20);
setTimeout(() => emitter.emit("message", "three"), 30);
let seen = 0;
for await (const [text] of on(emitter, "message")) {
console.log(text);
seen += 1;
if (seen === 3) break;
}
console.log("loop ended");one
two
three
loop endedThe iterator never ends by itself, because an emitter never says it is finished. You end the loop with break, return, a thrown error or an abort signal. Leaving the loop removes the listeners.
Events that arrive while the body is busy
The iterator buffers events that fire while your loop body is awaiting something else, then yields them in order.
import { EventEmitter, on } from "node:events";
import { setTimeout as sleep } from "node:timers/promises";
const emitter = new EventEmitter();
let count = 0;
setImmediate(() => {
emitter.emit("tick", 1);
emitter.emit("tick", 2);
emitter.emit("tick", 3);
});
for await (const [n] of on(emitter, "tick")) {
console.log("handling", n);
await sleep(10);
count += 1;
if (count === 3) break;
}handling 1
handling 2
handling 3Events 2 and 3 were emitted while the body was still waiting on event 1's sleep, and were queued. That is helpful, since nothing is lost, and dangerous: the buffer is unbounded by default, so a fast emitter with a slow consumer grows memory without limit. The events.on documentation lists highWaterMark and lowWaterMark options that pause a source exposing pause() and resume() methods; for a plain emitter, apply your own limit.
Ending the iteration with a close event
The close option takes event names that end the loop cleanly when emitted, which is the right way to model a stream that finishes.
import { EventEmitter, on } from "node:events";
const emitter = new EventEmitter();
setImmediate(() => {
emitter.emit("line", "first");
emitter.emit("line", "second");
emitter.emit("end");
});
for await (const [line] of on(emitter, "line", { close: ["end"] })) {
console.log(line);
}
console.log("finished");first
second
finishedThe end event completes the iterator after the buffered line events are consumed. Without close, this loop would wait forever.
Errors and signals with on
As with once, an error event rejects the pending iteration, which surfaces as an exception inside the for await, so one try and catch covers failures. A signal option does the same with an AbortError.
import { EventEmitter, on } from "node:events";
const emitter = new EventEmitter();
const controller = new AbortController();
setTimeout(() => emitter.emit("data", 1), 5);
setTimeout(() => controller.abort(), 20);
try {
for await (const [value] of on(emitter, "data", { signal: controller.signal })) {
console.log("data", value);
}
} catch (error) {
console.log("ended by", error.name);
}data 1
ended by AbortErrorWhen a plain listener is better
Use emitter.on when you handle every event independently and do not need ordering with await. A listener runs synchronously inside emit, so a handler that does quick work needs no promise. Use on from node:events when the handling is async and must run one event at a time, because the loop body finishes before the next event is processed.
| Need | Use |
|---|---|
| Wait for one event | events.once |
| Handle every event, quick synchronous work | emitter.on |
Handle every event sequentially with await | events.on with for await |
| Stop on a signal | signal option on either |
Common mistakes
**Registering once after the event fired.** The promise waits for the next occurrence. Create it before you trigger the action.
import { EventEmitter, once } from "node:events";
const emitter = new EventEmitter();
const ready = once(emitter, "ready"); // register first
emitter.emit("ready", "ok");
console.log(await ready);[ 'ok' ]Forgetting that the result is an array. Both functions give you the emit arguments as an array.
Leaving an unbounded buffer. A slow consumer and a fast emitter cost memory.
Never ending the loop. Use close, break or a signal.
Using the pair in a real program
A typical use of events.once is the start-up sequence of a service. The code creates a server, calls listen, and awaits the listening event before it prints the address or runs a health check, with an error event rejecting the same promise if the port is already in use. That reads as a straight line of code where the callback version would be a nest. The same shape works for child processes, where you await the spawn or exit event, and for sockets, where you await connect.
events.on suits long-lived consumers that must process messages one at a time: a line-oriented protocol over a socket, a stream of file system notifications or a queue of commands from a parent process. The loop body can await a database write for each message, and the iterator holds incoming events in order until the body is ready for the next.
Memory and listener hygiene
An emitter warns when more than ten listeners are attached to the same event, because that number is usually a leak. Code that calls once inside a loop, or inside a request handler, without a signal or a way to finish, can reach that limit and produce the warning. The fix is to make sure each wait ends: either the event arrives, or a signal aborts it. Both functions remove their listeners in either case, which is another reason to use them rather than hand-written promise wrappers. When you do see the warning, count the listeners with emitter.listenerCount(name) to find the one that is growing.


