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 <jasnell@gmail.com>

PR-URL: #40951
Reviewed-By: Benjamin Gruenbaum <benjamingr@gmail.com>
  • Loading branch information
jasnell authored and danielleadams committed Dec 13, 2021
1 parent 70e6fe8 commit 4ba883d
Show file tree
Hide file tree
Showing 3 changed files with 38 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 @@ -191,6 +191,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 @@ -116,6 +116,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 @@ -126,7 +132,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 @@ -224,7 +231,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
21 changes: 21 additions & 0 deletions test/parallel/test-abortcontroller.js
Original file line number Diff line number Diff line change
Expand Up @@ -230,3 +230,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 4ba883d

Please sign in to comment.