File tree Expand file tree Collapse file tree 3 files changed +40
-2
lines changed Expand file tree Collapse file tree 3 files changed +40
-2
lines changed Original file line number Diff line number Diff line change @@ -179,6 +179,14 @@ ac.abort(new Error('boom!'));
179179console .log (ac .signal .reason ); // Error('boom!');
180180```
181181
182+ #### ` abortSignal.throwIfAborted() `
183+
184+ <!-- YAML
185+ added: REPLACEME
186+ -->
187+
188+ If ` abortSignal.aborted ` is ` true ` , throws ` abortSignal.reason ` .
189+
182190## Class: ` Buffer `
183191
184192<!-- YAML
Original file line number Diff line number Diff line change @@ -141,6 +141,12 @@ class AbortSignal extends EventTarget {
141141 return this [ kReason ] ;
142142 }
143143
144+ throwIfAborted ( ) {
145+ if ( this . aborted ) {
146+ throw this . reason ;
147+ }
148+ }
149+
144150 [ customInspectSymbol ] ( depth , options ) {
145151 return customInspect ( this , {
146152 aborted : this . aborted
@@ -151,7 +157,8 @@ class AbortSignal extends EventTarget {
151157 * @param {any } reason
152158 * @returns {AbortSignal }
153159 */
154- static abort ( reason ) {
160+ static abort (
161+ reason = new DOMException ( 'This operation was aborted' , 'AbortError' ) ) {
155162 return createAbortSignal ( true , reason ) ;
156163 }
157164
@@ -311,7 +318,7 @@ class AbortController {
311318 /**
312319 * @param {any } reason
313320 */
314- abort ( reason ) {
321+ abort ( reason = new DOMException ( 'This operation was aborted' , 'AbortError' ) ) {
315322 validateAbortController ( this ) ;
316323 abortSignal ( this [ kSignal ] , reason ) ;
317324 }
Original file line number Diff line number Diff line change @@ -14,6 +14,8 @@ const {
1414const {
1515 kWeakHandler,
1616} = require ( 'internal/event_target' ) ;
17+ const { internalBinding } = require ( 'internal/test/binding' ) ;
18+ const { DOMException } = internalBinding ( 'messaging' ) ;
1719
1820const { setTimeout : sleep } = require ( 'timers/promises' ) ;
1921
@@ -230,3 +232,24 @@ const { setTimeout: sleep } = require('timers/promises');
230232 // keep the Node.js process open (the timer is unref'd)
231233 AbortSignal . timeout ( 1_200_000 ) ;
232234}
235+
236+ {
237+ // Test AbortSignal.reason default
238+ const signal = AbortSignal . abort ( ) ;
239+ ok ( signal . reason instanceof DOMException ) ;
240+ strictEqual ( signal . reason . code , 20 ) ;
241+
242+ const ac = new AbortController ( ) ;
243+ ac . abort ( ) ;
244+ ok ( ac . signal . reason instanceof DOMException ) ;
245+ strictEqual ( ac . signal . reason . code , 20 ) ;
246+ }
247+
248+ {
249+ // Test abortSignal.throwIfAborted()
250+ throws ( ( ) => AbortSignal . abort ( ) . throwIfAborted ( ) , { code : 20 } ) ;
251+
252+ // Does not throw because it's not aborted.
253+ const ac = new AbortController ( ) ;
254+ ac . signal . throwIfAborted ( ) ;
255+ }
You can’t perform that action at this time.
0 commit comments