-
Notifications
You must be signed in to change notification settings - Fork 29.8k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
events: extract addAbortListener for safe internal use
Refs: #48596 PR-URL: #52081 Reviewed-By: Moshe Atlow <[email protected]> Reviewed-By: Benjamin Gruenbaum <[email protected]> Reviewed-By: Antoine du Hamel <[email protected]> Reviewed-By: Luigi Pinca <[email protected]>
- Loading branch information
1 parent
ba06c5c
commit e263946
Showing
3 changed files
with
56 additions
and
29 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,54 @@ | ||
'use strict'; | ||
|
||
const { | ||
SymbolDispose, | ||
} = primordials; | ||
const { | ||
validateAbortSignal, | ||
validateFunction, | ||
} = require('internal/validators'); | ||
const { | ||
codes: { | ||
ERR_INVALID_ARG_TYPE, | ||
}, | ||
} = require('internal/errors'); | ||
|
||
let queueMicrotask; | ||
let kResistStopPropagation; | ||
|
||
/** | ||
* @param {AbortSignal} signal | ||
* @param {EventListener} listener | ||
* @returns {Disposable} | ||
*/ | ||
function addAbortListener(signal, listener) { | ||
if (signal === undefined) { | ||
throw new ERR_INVALID_ARG_TYPE('signal', 'AbortSignal', signal); | ||
} | ||
validateAbortSignal(signal, 'signal'); | ||
validateFunction(listener, 'listener'); | ||
|
||
let removeEventListener; | ||
if (signal.aborted) { | ||
queueMicrotask ??= require('internal/process/task_queues').queueMicrotask; | ||
queueMicrotask(() => listener()); | ||
} else { | ||
kResistStopPropagation ??= require('internal/event_target').kResistStopPropagation; | ||
// TODO(atlowChemi) add { subscription: true } and return directly | ||
signal.addEventListener('abort', listener, { __proto__: null, once: true, [kResistStopPropagation]: true }); | ||
removeEventListener = () => { | ||
signal.removeEventListener('abort', listener); | ||
}; | ||
} | ||
return { | ||
__proto__: null, | ||
[SymbolDispose]() { | ||
removeEventListener?.(); | ||
}, | ||
}; | ||
} | ||
|
||
module.exports = { | ||
__proto__: null, | ||
addAbortListener, | ||
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters