How do I cancel an HTTP fetch() request?

前端 未结 6 1680
小蘑菇
小蘑菇 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:40

    TL/DR:

    fetch now supports a signal parameter as of 20 September 2017, but not all browsers seem support this at the moment.

    2020 UPDATE: Most major browsers (Edge, Firefox, Chrome, Safari, Opera, and a few others) support the feature, which has become part of the DOM living standard. (as of 5 March 2020)

    This is a change we will be seeing very soon though, and so you should be able to cancel a request by using an AbortControllers AbortSignal.

    Long Version

    How to:

    The way it works is this:

    Step 1: You create an AbortController (For now I just used this)

    const controller = new AbortController()

    Step 2: You get the AbortControllers signal like this:

    const signal = controller.signal

    Step 3: You pass the signal to fetch like so:

    fetch(urlToFetch, {
        method: 'get',
        signal: signal, // <------ This is our AbortSignal
    })
    

    Step 4: Just abort whenever you need to:

    controller.abort();

    Here's an example of how it would work (works on Firefox 57+):

    
    
    
    
    

    Example of fetch abort


    Sources:

    • The final version of AbortController has been added to the DOM specification
    • The corresponding PR for the fetch specification is now merged.
    • Browser bugs tracking the implementation of AbortController is available here: Firefox: #1378342, Chromium: #750599, WebKit: #174980, Edge: #13009916.

提交回复
热议问题