@@ -31,6 +31,7 @@ A light-weight module that brings `window.fetch` to Node.js
31
31
- [ Accessing Headers and other Meta data] ( #accessing-headers-and-other-meta-data )
32
32
- [ Post data using a file stream] ( #post-data-using-a-file-stream )
33
33
- [ Post with form-data (detect multipart)] ( #post-with-form-data-detect-multipart )
34
+ - [ Request cancellation with AbortSignal] ( #request-cancellation-with-abortsignal )
34
35
- [ API] ( #api )
35
36
- [ fetch(url[ , options] )] ( #fetchurl-options )
36
37
- [ Options] ( #options )
@@ -248,6 +249,40 @@ fetch('https://httpbin.org/post', options)
248
249
.then (json => console .log (json));
249
250
```
250
251
252
+ #### Request cancellation with AbortSignal
253
+
254
+ > NOTE: You may only cancel streamed requests on Node >= v8.0.0
255
+
256
+ You may cancel requests with ` AbortController ` . A suggested implementation is [ ` abort-controller ` ] ( https://www.npmjs.com/package/abort-controller ) .
257
+
258
+ An example of timing out a request after 150ms could be achieved as follows:
259
+
260
+ ``` js
261
+ import AbortContoller from ' abort-controller' ;
262
+
263
+ const controller = new AbortController ();
264
+ const timeout = setTimeout (
265
+ () => { controller .abort (); },
266
+ 150 ,
267
+ );
268
+
269
+ fetch (url, { signal: controller .signal })
270
+ .then (res => res .json ())
271
+ .then (
272
+ data => {
273
+ useData (data)
274
+ },
275
+ err => {
276
+ if (err .name === ' AbortError' ) {
277
+ // request was aborted
278
+ }
279
+ },
280
+ )
281
+ .finally (() => {
282
+ clearTimeout (timeout);
283
+ });
284
+ ```
285
+
251
286
See [ test cases] ( https://github.com/bitinn/node-fetch/blob/master/test/test.js ) for more examples.
252
287
253
288
@@ -286,40 +321,6 @@ The default values are shown after each option key.
286
321
}
287
322
```
288
323
289
- #### Request cancellation with AbortController:
290
-
291
- > NOTE: You may only cancel streamed requests on Node >= v8.0.0
292
-
293
- You may cancel requests with ` AbortController ` . A suggested implementation is [ ` abort-controller ` ] ( https://www.npmjs.com/package/abort-controller ) .
294
-
295
- An example of timing out a request after 150ms could be achieved as follows:
296
-
297
- ``` js
298
- import AbortContoller from ' abort-controller' ;
299
-
300
- const controller = new AbortController ();
301
- const timeout = setTimeout (
302
- () => { controller .abort (); },
303
- 150 ,
304
- );
305
-
306
- fetch (url, { signal: controller .signal })
307
- .then (res => res .json ())
308
- .then (
309
- data => {
310
- useData (data)
311
- },
312
- err => {
313
- if (err .name === ' AbortError' ) {
314
- // request was aborted
315
- }
316
- },
317
- )
318
- .finally (() => {
319
- clearTimeout (timeout);
320
- });
321
- ```
322
-
323
324
##### Default Headers
324
325
325
326
If no values are set, the following request headers will be sent automatically:
0 commit comments