Clean up listener and timeout after waitfor reject
This commit is contained in:
+14
-7
@@ -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);
|
||||
}
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user