How do I cancel an HTTP fetch() request?

前端 未结 6 1711
小蘑菇
小蘑菇 2020-11-22 14:58

There is a new API for making requests from JavaScript: fetch(). Is there any built in mechanism for canceling these requests in-flight?

6条回答
  •  盖世英雄少女心
    2020-11-22 15:41

    https://developers.google.com/web/updates/2017/09/abortable-fetch

    https://dom.spec.whatwg.org/#aborting-ongoing-activities

    // setup AbortController
    const controller = new AbortController();
    // signal to pass to fetch
    const signal = controller.signal;
    
    // fetch as usual
    fetch(url, { signal }).then(response => {
      ...
    }).catch(e => {
      // catch the abort if you like
      if (e.name === 'AbortError') {
        ...
      }
    });
    
    // when you want to abort
    controller.abort();
    

    works in edge 16 (2017-10-17), firefox 57 (2017-11-14), desktop safari 11.1 (2018-03-29), ios safari 11.4 (2018-03-29), chrome 67 (2018-05-29), and later.


    on older browsers, you can use github's whatwg-fetch polyfill and AbortController polyfill. you can detect older browsers and use the polyfills conditionally, too:

    import 'abortcontroller-polyfill/dist/abortcontroller-polyfill-only'
    import {fetch} from 'whatwg-fetch'
    
    // use native browser implementation if it supports aborting
    const abortableFetch = ('signal' in new Request('')) ? window.fetch : fetch
    

提交回复
热议问题