Skip to content

非公式 / UnofficialCloudflare, Inc. 非提携。アカウント情報は入力しないでください。Not affiliated with Cloudflare, Inc. Do not enter Cloudflare credentials here.Official docsこのサイトについてプライバシー

EventEmitter

最終更新 Markdown で表示Agent セットアップ

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 ↗ オプションも含みます。これにより、イベントハンドラーとしての非同期関数の扱いが改善されます。

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 ドキュメント ↗ を参照してください。

役に立ちましたか?