How do I cancel an HTTP fetch() request?

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

    Let's polyfill:

    if(!AbortController){
      class AbortController {
        constructor() {
          this.aborted = false;
          this.signal = this.signal.bind(this);
        }
        signal(abortFn, scope) {
          if (this.aborted) {
            abortFn.apply(scope, { name: 'AbortError' });
            this.aborted = false;
          } else {
            this.abortFn = abortFn.bind(scope);
          }
        }
        abort() {
          if (this.abortFn) {
            this.abortFn({ reason: 'canceled' });
            this.aborted = false;
          } else {
            this.aborted = true;
          }
        }
      }
    
      const originalFetch = window.fetch;
    
      const customFetch = (url, options) => {
        const { signal } = options || {};
    
        return new Promise((resolve, reject) => {
          if (signal) {
            signal(reject, this);
          }
          originalFetch(url, options)
            .then(resolve)
            .catch(reject);
        });
      };
    
      window.fetch = customFetch;
    }
    

    Please have in mind that the code is not tested! Let me know if you have tested it and something didn't work. It may give you warnings that you try to overwrite the 'fetch' function from the JavaScript official library.

提交回复
热议问题