Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add wait method #3

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 21 additions & 1 deletion mod.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ export class EventEmitter<E extends Record<string, unknown[]>> {
#listeners: {
[K in keyof E]?: Array<{
once: boolean;
cb: (...args: E[K]) => void;
cb: (...args: E[K]) => void | Promise<void>;
}>;
} = {};
#globalWriters: WritableStreamDefaultWriter<Entry<E, keyof E>>[] = [];
Expand Down Expand Up @@ -183,6 +183,26 @@ export class EventEmitter<E extends Record<string, unknown[]>> {
}
}

/**
* 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<K extends keyof E>(eventName: K, ...args: E[K]): Promise<void> {
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]<K extends keyof E>(): AsyncIterableIterator<
{ [V in K]: Entry<E, V> }[K]
> {
Expand Down
16 changes: 15 additions & 1 deletion test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -171,7 +171,7 @@ Deno.test("closeMixed", async () => {
}
})();

for await (const x of ee) {
for await (const _ of ee) {
await ee.off();
}
});
Expand All @@ -182,3 +182,17 @@ Deno.test("limitReached", () => {
ee.on("foo", () => {});
assertThrows(() => ee.on("foo", () => {}));
});

Deno.test("wait", async () => {
const ee = new EventEmitter<Events>();

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);
});