lib: add abortSignal.throwIfAborted()

Refs: https://github.com/whatwg/dom/pull/1034
Signed-off-by: James M Snell <jasnell@gmail.com>

PR-URL: https://github.com/nodejs/node/pull/40951
Reviewed-By: Benjamin Gruenbaum <benjamingr@gmail.com>
This commit is contained in:
James M Snell 2021-11-24 07:28:30 -08:00
parent 03c9837457
commit 3f72c72bbb
No known key found for this signature in database
GPG Key ID: 7341B15C070877AC
3 changed files with 38 additions and 2 deletions

View File

@ -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

View File

@ -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
@ -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);
}
@ -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);
}

View File

@ -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();
}