Node.js

Await one EventEmitter event

Use events.once to await a single EventEmitter event. Register the wait before triggering the event so a synchronous emission cannot happen before the listener exists.

Worked example

Node.js example · save as example.mjs and run node example.mjs

import {EventEmitter, once} from "node:events";
const emitter = new EventEmitter();
const waiting = once(emitter, "ready");
emitter.emit("ready", 42);
const [value] = await waiting;
console.log(value);

How it works

Once resolves with an array of the emitted event arguments. The promise is created before emit because EventEmitter listeners run synchronously. That ordering is essential when a ready signal could be emitted immediately during setup.

Limits and mistakes

When waiting for another event, an error event can reject the promise. A missing event can leave it pending indefinitely; use cancellation where needed. For multiple synchronously emitted events, establish all required waits before yielding control.

Check the result

Expect 42. Move emit before listener registration only in a bounded test to demonstrate the missed-event problem; do not leave an unbounded wait running.

Sources

Reference documentation for the behavior used in this guide: