Skip to content

Commit 416dafb

Browse files
committed
util: allow safely adding listener to abortSignal
1 parent e8810b9 commit 416dafb

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed

lib/util.js

+24
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,7 @@ const {
4343
ObjectValues,
4444
ReflectApply,
4545
StringPrototypePadStart,
46+
SymbolDispose,
4647
} = primordials;
4748

4849
const {
@@ -63,6 +64,7 @@ const {
6364
} = require('internal/util/inspect');
6465
const { debuglog } = require('internal/util/debuglog');
6566
const {
67+
validateAbortSignal,
6668
validateFunction,
6769
validateNumber,
6870
} = require('internal/validators');
@@ -73,6 +75,7 @@ const {
7375
deprecate,
7476
getSystemErrorMap,
7577
getSystemErrorName: internalErrorName,
78+
kEmptyObject,
7679
promisify,
7780
toUSVString,
7881
defineLazyProperties,
@@ -86,6 +89,7 @@ function lazyAbortController() {
8689
}
8790

8891
let internalDeepEqual;
92+
let kResistStopPropagation;
8993

9094
/**
9195
* @deprecated since v4.0.0
@@ -345,11 +349,31 @@ function getSystemErrorName(err) {
345349
return internalErrorName(err);
346350
}
347351

352+
function addSafeAbortSignalAbortListener(signal, listener, options = kEmptyObject) {
353+
if (signal === undefined) {
354+
throw new ERR_INVALID_ARG_TYPE('signal', 'AbortSignal', signal)
355+
}
356+
validateAbortSignal(signal, 'signal');
357+
kResistStopPropagation ??= require('internal/event_target').kResistStopPropagation;
358+
signal.addEventListener('abort', listener, { ...options, [kResistStopPropagation]: true });
359+
const removeEventListener = () => {
360+
signal.removeEventListener('abort', listener, options);
361+
};
362+
return {
363+
__proto__: null,
364+
removeEventListener,
365+
[SymbolDispose]() {
366+
removeEventListener();
367+
},
368+
};
369+
}
370+
348371
// Keep the `exports =` so that various functions can still be monkeypatched
349372
module.exports = {
350373
_errnoException: errnoException,
351374
_exceptionWithHostPort: exceptionWithHostPort,
352375
_extend,
376+
addSafeAbortSignalAbortListener,
353377
callbackify,
354378
debug: debuglog,
355379
debuglog,

0 commit comments

Comments
 (0)