Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

lib: add abortSignal.throwIfAborted() #40951

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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();
}