Skip to content

Commit 4ba883d

Browse files
jasnelldanielleadams
authored andcommitted
lib: add abortSignal.throwIfAborted()
Refs: whatwg/dom#1034 Signed-off-by: James M Snell <[email protected]> PR-URL: #40951 Reviewed-By: Benjamin Gruenbaum <[email protected]>
1 parent 70e6fe8 commit 4ba883d

File tree

3 files changed

+38
-2
lines changed

3 files changed

+38
-2
lines changed

doc/api/globals.md

+8
Original file line numberDiff line numberDiff line change
@@ -191,6 +191,14 @@ ac.abort(new Error('boom!'));
191191
console.log(ac.signal.reason); // Error('boom!');
192192
```
193193

194+
#### `abortSignal.throwIfAborted()`
195+
196+
<!-- YAML
197+
added: REPLACEME
198+
-->
199+
200+
If `abortSignal.aborted` is `true`, throws `abortSignal.reason`.
201+
194202
## Class: `Buffer`
195203

196204
<!-- YAML

lib/internal/abort_controller.js

+9-2
Original file line numberDiff line numberDiff line change
@@ -116,6 +116,12 @@ class AbortSignal extends EventTarget {
116116
return this[kReason];
117117
}
118118

119+
throwIfAborted() {
120+
if (this.aborted) {
121+
throw this.reason;
122+
}
123+
}
124+
119125
[customInspectSymbol](depth, options) {
120126
return customInspect(this, {
121127
aborted: this.aborted
@@ -126,7 +132,8 @@ class AbortSignal extends EventTarget {
126132
* @param {any} reason
127133
* @returns {AbortSignal}
128134
*/
129-
static abort(reason) {
135+
static abort(
136+
reason = new DOMException('This operation was aborted', 'AbortError')) {
130137
return createAbortSignal(true, reason);
131138
}
132139

@@ -224,7 +231,7 @@ class AbortController {
224231
/**
225232
* @param {any} reason
226233
*/
227-
abort(reason) {
234+
abort(reason = new DOMException('This operation was aborted', 'AbortError')) {
228235
validateAbortController(this);
229236
abortSignal(this[kSignal], reason);
230237
}

test/parallel/test-abortcontroller.js

+21
Original file line numberDiff line numberDiff line change
@@ -230,3 +230,24 @@ const { setTimeout: sleep } = require('timers/promises');
230230
// keep the Node.js process open (the timer is unref'd)
231231
AbortSignal.timeout(1_200_000);
232232
}
233+
234+
{
235+
// Test AbortSignal.reason default
236+
const signal = AbortSignal.abort();
237+
ok(signal.reason instanceof DOMException);
238+
strictEqual(signal.reason.code, 20);
239+
240+
const ac = new AbortController();
241+
ac.abort();
242+
ok(ac.signal.reason instanceof DOMException);
243+
strictEqual(ac.signal.reason.code, 20);
244+
}
245+
246+
{
247+
// Test abortSignal.throwIfAborted()
248+
throws(() => AbortSignal.abort().throwIfAborted(), { code: 20 });
249+
250+
// Does not throw because it's not aborted.
251+
const ac = new AbortController();
252+
ac.signal.throwIfAborted();
253+
}

0 commit comments

Comments
 (0)