跳转到内容
搜索文档

EventEmitter

最后更新 查看 MarkdownAgent 设置

EventEmitter 是一个发出命名事件并触发监听器调用的对象。

import { EventEmitter } from "node:events";

const emitter = new EventEmitter();
emitter.on("hello", (...args) => {
	console.log(...args); // 1 2 3
});

emitter.emit("hello", 1, 2, 3);

Workers 运行时的实现支持完整的 Node.js EventEmitter API,包括 captureRejections 选项,可更好地处理作为事件处理器的 async 函数:

const emitter = new EventEmitter({ captureRejections: true });
emitter.on("hello", async (...args) => {
	throw new Error("boom");
});
emitter.on("error", (err) => {
	// the async promise rejection is emitted here!
});

与 Node.js 一样,当 EventEmitter 上发出 'error' 事件且没有监听器时,错误会立即抛出。但在 Node.js 中,可以在 process 对象上为 'uncaughtException' 事件添加处理器以捕获全局未捕获异常。然而,'uncaughtException' 事件目前在 Workers 运行时中尚未实现。强烈建议始终为任何 EventEmitter 实例添加 'error' 监听器。

更多信息请参阅 Node.js EventEmitter 文档

这篇文档对您有帮助吗?