mirror of
https://github.com/nodejs/node.git
synced 2024-11-21 10:59:27 +00:00
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:
parent
03c9837457
commit
3f72c72bbb
@ -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
|
||||
|
@ -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);
|
||||
}
|
||||
|
@ -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();
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user