Skip to content

Commit

Permalink
lib: add abortSignal.throwIfAborted()
Browse files Browse the repository at this point in the history
Refs: whatwg/dom#1034
Signed-off-by: James M Snell <[email protected]>

PR-URL: #40951
Reviewed-By: Benjamin Gruenbaum <[email protected]>
  • Loading branch information
jasnell authored and targos committed Aug 1, 2022
1 parent acc68c9 commit fde5e05
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 2 deletions.
8 changes: 8 additions & 0 deletions doc/api/globals.md
Original file line number Diff line number Diff line change
Expand Up @@ -179,6 +179,14 @@ ac.abort(new Error('boom!'));
console.log(ac.signal.reason); // Error('boom!');
```

#### `abortSignal.throwIfAborted()`

<!-- YAML
added: REPLACEME
-->

If `abortSignal.aborted` is `true`, throws `abortSignal.reason`.

## Class: `Buffer`

<!-- YAML
Expand Down
11 changes: 9 additions & 2 deletions lib/internal/abort_controller.js
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,12 @@ class AbortSignal extends EventTarget {
return this[kReason];
}

throwIfAborted() {
if (this.aborted) {
throw this.reason;
}
}

[customInspectSymbol](depth, options) {
return customInspect(this, {
aborted: this.aborted
Expand All @@ -151,7 +157,8 @@ class AbortSignal extends EventTarget {
* @param {any} reason
* @returns {AbortSignal}
*/
static abort(reason) {
static abort(
reason = new DOMException('This operation was aborted', 'AbortError')) {
return createAbortSignal(true, reason);
}

Expand Down Expand Up @@ -311,7 +318,7 @@ class AbortController {
/**
* @param {any} reason
*/
abort(reason) {
abort(reason = new DOMException('This operation was aborted', 'AbortError')) {
validateAbortController(this);
abortSignal(this[kSignal], reason);
}
Expand Down
23 changes: 23 additions & 0 deletions test/parallel/test-abortcontroller.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ const {
const {
kWeakHandler,
} = require('internal/event_target');
const { internalBinding } = require('internal/test/binding');
const { DOMException } = internalBinding('messaging');

const { setTimeout: sleep } = require('timers/promises');

Expand Down Expand Up @@ -230,3 +232,24 @@ const { setTimeout: sleep } = require('timers/promises');
// keep the Node.js process open (the timer is unref'd)
AbortSignal.timeout(1_200_000);
}

{
// Test AbortSignal.reason default
const signal = AbortSignal.abort();
ok(signal.reason instanceof DOMException);
strictEqual(signal.reason.code, 20);

const ac = new AbortController();
ac.abort();
ok(ac.signal.reason instanceof DOMException);
strictEqual(ac.signal.reason.code, 20);
}

{
// Test abortSignal.throwIfAborted()
throws(() => AbortSignal.abort().throwIfAborted(), { code: 20 });

// Does not throw because it's not aborted.
const ac = new AbortController();
ac.signal.throwIfAborted();
}

0 comments on commit fde5e05

Please sign in to comment.