From 504540df71e46378b72addd0b09f11dd966f820f Mon Sep 17 00:00:00 2001 From: Sadie Dotzler Date: Mon, 27 Jun 2022 22:33:44 -0700 Subject: [PATCH 1/3] fix inconsistent naming --- test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test.ts b/test.ts index 5bcbb18..c8c615f 100644 --- a/test.ts +++ b/test.ts @@ -171,7 +171,7 @@ Deno.test("closeMixed", async () => { } })(); - for await (const x of ee) { + for await (const _ of ee) { await ee.off(); } }); From 577d5a0a3101a70a3908c46996bfb2f05d4b2f40 Mon Sep 17 00:00:00 2001 From: Sadie Dotzler Date: Mon, 27 Jun 2022 23:01:47 -0700 Subject: [PATCH 2/3] implement wait method --- mod.ts | 22 +++++++++++++++++++++- 1 file changed, 21 insertions(+), 1 deletion(-) diff --git a/mod.ts b/mod.ts index d397aa6..c4bde87 100644 --- a/mod.ts +++ b/mod.ts @@ -9,7 +9,7 @@ export class EventEmitter> { #listeners: { [K in keyof E]?: Array<{ once: boolean; - cb: (...args: E[K]) => void; + cb: (...args: E[K]) => void | Promise; }>; } = {}; #globalWriters: WritableStreamDefaultWriter>[] = []; @@ -183,6 +183,26 @@ export class EventEmitter> { } } + /** + * Call and, if async, await the completion of the listeners registered for + * the event named eventName, in the order they were registered, passing the + * supplied arguments to each. Returns a Promise that resolves on the completion + * of the last listener. + * + * Does not support being awaited the same was as `emit`. + */ + async wait(eventName: K, ...args: E[K]): Promise { + const listeners = this.#listeners[eventName]?.slice() ?? []; + for (const { cb, once } of listeners) { + const ret = cb(...args); + if (ret) await ret; + + if (once) { + this.off(eventName, cb); + } + } + } + [Symbol.asyncIterator](): AsyncIterableIterator< { [V in K]: Entry }[K] > { From 9c56011a78e93b731213a8e10dcc9bf1324921c4 Mon Sep 17 00:00:00 2001 From: Sadie Dotzler Date: Mon, 27 Jun 2022 23:06:28 -0700 Subject: [PATCH 3/3] add test for wait method --- test.ts | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/test.ts b/test.ts index c8c615f..708f9f7 100644 --- a/test.ts +++ b/test.ts @@ -182,3 +182,17 @@ Deno.test("limitReached", () => { ee.on("foo", () => {}); assertThrows(() => ee.on("foo", () => {})); }); + +Deno.test("wait", async () => { + const ee = new EventEmitter(); + + ee.on("foo", async () => { + console.log("foo"); + await new Promise((resolve) => setTimeout(resolve, 1000)); + }).on("bar", () => { + console.log("bar"); + }); + + await ee.wait("foo", "baz"); + await ee.wait("bar", 0); +});