Clean up listener and timeout after waitfor reject

This commit is contained in:
2026-08-10 02:32:17 +00:00
parent 296ab4aadf
commit bc28a7e96a
2 changed files with 79 additions and 7 deletions
+14 -7
View File
@@ -190,22 +190,29 @@ export class EventEmitter<T extends EventMap> {
return new Promise((resolve, reject) => {
let timeoutId: ReturnType<typeof setTimeout> | undefined;
// Create a cleanup function to remove the listener and clear the timeout if it is still pending.
const cleanup = (listener: Listener<T[K]>): void => {
// Remove the listener from the listeners map.
this.off(type, listener);
// Clear the timeout if it is still pending.
if (timeoutId !== undefined) {
clearTimeout(timeoutId);
}
};
// Create a listener function.
const listener = (payload: Readonly<T[K]>): void => {
const listener = (payload: DeeplyReadonly<T[K]>): void => {
try {
// If the event payload does not match the predicate condition, return.
if (!predicate(payload)) {
return;
}
// Clean up
this.off(type, listener);
if (timeoutId !== undefined) {
clearTimeout(timeoutId);
}
cleanup(listener);
resolve(payload);
} catch (error) {
cleanup(listener);
reject(error);
}
};