AbortController():AbortController()构造函数创建一个新的 AbortController 对象实例

let controller = new AbortController();
let signal = controller.signal; //signal 的初始状态
//中止请求
controller.abort();

注意:

1. AbortController浏览器兼容性

 

2.Chrome 内:

  • 同一 AbortController 实例,只能 abort 请求一次,后面就不能重发 request;
  • 不同 AbortController 实例,可以 abort 请求多次,single 实例打印正常,请求能够中断,但是不会显示cancel;

signal:signal 属性返回一个 AbortSignal 对象实例,它可以用来查看一个Web(网络)请求的状态

abort():终止一个尚未完成的Web(网络)请求,它能够终止 fetch 请求,任何响应Body的消费者和流

<script>
import { ref,toRefs, reactive, onMounted, onUpdated, onUnmounted } from 'vue'

export default {
  setup(props, ctx) {
    const url = '/api/xxx';
    const obj = ref({ msg: ''});

    const controller = new AbortController();
    let signal = controller.signal;
    console.log('Original signal:', signal);

    const download = function fetchVideo() {
      fetch(url)
        .then(response => response.json())
        .then(function(response) {
          console.log('res:', response.message);
          obj.value.msg = response.message;
        }).catch(function(e) {
          obj.msg = 'Download error: ' + e.message;
        })
    };
    const abortRequest = () => {
      controller.abort();
      console.log('Abort signal:', signal);
    }
    onMounted(() => {
      console.log('mounted!')
    });
    return {download, obj, abortRequest}
  }
}
</script>

<template>
  <h3>Using fetch</h3>
  <div class="wrapper">
    <button @click="download()" class="download">download</button>
    <button @click="abortRequest(e)" class="abort">abort request</button>
  </div>
  <div>{{obj.msg}}</div>

</template>

Axios 使用方式1:

使用 CancelToken.souce 工厂方法创建一个 cancel token

<script>
import { ref, onMounted } from 'vue';
import axios from 'axios';
export default {
  setup(props, context) {
    const CancelToken = axios.CancelToken;
    const source = CancelToken.source();
    const URL = 'http://localhost:xxx/xxx';

    const download = () => {
      axios.get(URL, {
        cancelToken: source.token
      }).catch(function (thrown) {
        // 判断请求是否已中止
        if (axios.isCancel(thrown)) {
          // 参数 thrown 是自定义的信息
          console.log('Request canceled', thrown.message);
        } else {
          // 处理错误
        }
      });
    };

    const abortRequest = () => {
      source.cancel('Operation canceled by the user.');
      console.log('abort')
    };

    onMounted((a, b) => {
    })

    return {
      download,
      abortRequest
    }
  }
}
</script>

<template>
<hr />
<h3>2.1 Using Axios</h3>

<div class="wrapper">
  <button @click="download()" class="download">download</button>
  <button @click="abortRequest(e)" class="abort">abort request</button>
</div>

</template>

效果和fetch相同

Axios 使用方式2: (建议采用)

通过传递一个 executor 函数到 CancelToken 的构造函数来创建一个 cancel token:

使用 Axios.CancelToken (基于promise) 能达到每次触发请求并中断的目的,建议采用Axios 方式二

<script>
import { ref, onMounted } from 'vue';
import axios from 'axios';
export default {
  setup(props, context) {
    const CancelToken = axios.CancelToken;
    let cancel;
    const URL = '/api/xxx';

    const download = () => {
      axios.get(URL, {
        cancelToken: new CancelToken(function executor(c) {
          // executor 函数接收一个 cancel 函数作为参数
          cancel = c;
        })
      }).catch(function (thrown) {
        // 判断请求是否已中止
        if (axios.isCancel(thrown)) {
          // 参数 thrown 是自定义的信息
          console.log('Request canceled', thrown.message);
        } else {
          // 处理错误
          console.log('Handle the error');
        }
      });
    };

    const abortRequest = () => {
      cancel('Operation canceled by the user.');
      console.log('abort')
    };

    onMounted((a, b) => {
      
    })

    return {
      download,
      abortRequest
    }
  }
}
</script>

<template>
<hr />
<h3>2.2 Using Axios.</h3>

<div class="wrapper">
  <button @click="download()" class="download">download</button>
  <button @click="abortRequest(e)" class="abort">abort request</button>
</div>

</template>

最后注意:中断HTTP requests,只对HTTP 请求生效,服务端逻辑已经被触发的情况下,是需要服务端根据http 的监听来中断逻辑执行的。