How do I cancel an HTTP fetch() request?

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

    As for now there is no proper solution, as @spro says.

    However, if you have an in-flight response and are using ReadableStream, you can close the stream to cancel the request.

    fetch('http://example.com').then((res) => {
      const reader = res.body.getReader();
    
      /*
       * Your code for reading streams goes here
       */
    
      // To abort/cancel HTTP request...
      reader.cancel();
    });
    

提交回复
热议问题