Skip to content

Commit 02cc0ee

Browse files
committed
lib: add abortSignal.throwIfAborted()
Refs: whatwg/dom#1034 Signed-off-by: James M Snell <[email protected]>
1 parent 7633c86 commit 02cc0ee

File tree

3 files changed

+38
-2
lines changed

3 files changed

+38
-2
lines changed

doc/api/globals.md

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -180,6 +180,14 @@ ac.abort(new Error('boom!'));
180180
console.log(ac.signal.reason); // Error('boom!');
181181
```
182182

183+
#### `abortSignal.throwIfAborted()`
184+
185+
<!-- YAML
186+
added: REPLACEME
187+
-->
188+
189+
If `abortSignal.aborted` is `true`, throws `abortSignal.reason`.
190+
183191
## Class: `Buffer`
184192

185193
<!-- YAML

lib/internal/abort_controller.js

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,10 @@ const {
2929
}
3030
} = require('internal/errors');
3131

32+
const {
33+
DOMException,
34+
} = internalBinding('messaging');
35+
3236
const kAborted = Symbol('kAborted');
3337
const kReason = Symbol('kReason');
3438

@@ -69,6 +73,12 @@ class AbortSignal extends EventTarget {
6973
return this[kReason];
7074
}
7175

76+
throwIfAborted() {
77+
if (this.aborted) {
78+
throw this.reason;
79+
}
80+
}
81+
7282
[customInspectSymbol](depth, options) {
7383
return customInspect(this, {
7484
aborted: this.aborted
@@ -79,7 +89,8 @@ class AbortSignal extends EventTarget {
7989
* @param {any} reason
8090
* @returns {AbortSignal}
8191
*/
82-
static abort(reason) {
92+
static abort(
93+
reason = new DOMException('This operation was aborted', 'AbortError')) {
8394
return createAbortSignal(true, reason);
8495
}
8596
}
@@ -141,7 +152,7 @@ class AbortController {
141152
/**
142153
* @param {any} reason
143154
*/
144-
abort(reason) {
155+
abort(reason = new DOMException('This operation was aborted', 'AbortError')) {
145156
validateAbortController(this);
146157
abortSignal(this[kSignal], reason);
147158
}

test/parallel/test-abortcontroller.js

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -153,3 +153,20 @@ const { ok, strictEqual, throws } = require('assert');
153153
const signal = AbortSignal.abort('reason');
154154
strictEqual(signal.reason, 'reason');
155155
}
156+
157+
{
158+
// Test AbortSignal.reason default
159+
const signal = AbortSignal.abort();
160+
ok(signal.reason instanceof DOMException);
161+
strictEqual(signal.reason.code, 20);
162+
163+
const ac = new AbortController();
164+
ac.abort();
165+
ok(ac.signal.reason instanceof DOMException);
166+
strictEqual(ac.signal.reason.code, 20);
167+
}
168+
169+
{
170+
// Test abortSignal.throwIfAborted()
171+
throws(() => AbortSignal.abort().throwIfAborted(), { code: 20 });
172+
}

0 commit comments

Comments
 (0)