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.
Code
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: productionHow 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:eventsis 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
DOM Event Propagation VisualizerVisualize DOM event capturing, targeting, and bubbling phases in real time. Toggle stopPropagation and stopImmediatePropagation to see how events traverse the tree.HTTP Retry & Backoff CalculatorSimulate exponential backoff retry schedules with Full, Equal, Decorrelated, or No Jitter to inspect per-attempt wait times and cumulative latency.
FAQ
- Does this require external packages?
- No — `node:events` is a Node.js built-in module; nothing to install.
Report a problem with this exampleOpens a pre-filled issue on GitHub.