events.once Awaits A Single Emission

Await a one-shot event with events.once instead of wiring resolve callbacks by hand, and pass an AbortSignal so a listener that never fires cannot hang.

JavascriptResilience

Code

javascriptsnippet
23 lines
import { once, EventEmitter } from "node:events";

const bus = new EventEmitter();

// events.once 把一次性事件变成 await:省掉手写 resolve 回调
const started = once(bus, "ready").then(([payload]) => {
  console.log(`ready payload: ${payload.env}`);
  return payload.env;
});
bus.emit("ready", { env: "production" });

const env = await started;

// 永不触发的事件会挂死等待:给 once 配一个 AbortSignal 兜底
const controller = new AbortController();
const guarded = once(bus, "later", { signal: controller.signal }).catch((error) => {
  console.log(`later aborted: ${error.name === "AbortError"}`);
});
controller.abort();
await guarded;

console.log(`env was: ${env}`);

Output

Captured from a sandboxed run of this snippet in the build pipeline.

ready payload: production
later aborted: true
env was: production

How it works

Asynchronous boundaries use await, so failures surface as rejected promises at the call site instead of being swallowed. once, EventEmitter come from node:events — Node.js core modules the runtime ships with.

The demo data lives in module-level bindings: bus, started, env, controller.

What to watch for

  • node:events is a Node.js built-in module — it ships with the runtime, so there is nothing to install.

Using it

Running the file prints labeled results such as ready payload: $, later aborted: $, env was: $ — each operation’s effect is visible in the output.

Key statements

const guarded = once(bus, "later", { signal: controller.signal }).catch((error) => {
console.log(`later aborted: ${error.name === "AbortError"}`);
});
const started = once(bus, "ready").then(([payload]) => {
console.log(`ready payload: ${payload.env}`);
return payload.env;
});
const controller = new AbortController();

Interactive Tools for This Topic

FAQ

Does this require external packages?
No — `node:events` is a Node.js built-in module; nothing to install.