前端热门技术——axios详细讲解

Posted 清颖~

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了前端热门技术——axios详细讲解相关的知识,希望对你有一定的参考价值。

上一篇总结了axios的基本使用,请点击这里
今天呢,我们来讲一下 如何取消axios的异步请求

一、AbortController

从 v0.22.0 开始,Axios 支持 AbortController 以 fetch API 的方式取消请求:

const controller = new AbortController();

axios.get('/foo/bar', 
   signal: controller.signal
).then(function(response) 
   //...
);
// cancel the request
controller.abort()

二、CancelToken取消请求

使用 CancelToken 取消请求的方法在v0.22.0已废弃并不被推荐使用了。但我们开发中有的项目使用的版本还比较旧,是0.22.0以前的版本,所以,我们维护和开发老项目时,还是要了解该用法的。
官方原文:

You can also cancel a request using a CancelToken.
The axios cancel token API is based on the withdrawn cancelable promises proposal.
This API is deprecated since v0.22.0 and shouldn’t be used in new projects

方法一:
可以使用 CancelToken.source 工厂创建取消令牌

const CancelToken = axios.CancelToken;
const source = CancelToken.source();

axios.get('/user/12345', 
  cancelToken: source.token
).catch(function (thrown) 
  if (axios.isCancel(thrown)) 
    console.log('Request canceled', thrown.message);
   else 
    // handle error
  
);

axios.post('/user/12345', 
  name: 'new name'
, 
  cancelToken: source.token
)

// cancel the request (the message parameter is optional)
source.cancel('Operation canceled by the user.');

方法二:
还可以通过将执行器函数传递给 CancelToken 构造函数来创建取消CancelToken

const CancelToken = axios.CancelToken;
let cancel;
axios.get('/user/12345', 
  cancelToken: new CancelToken(function executor(c) 
    // An executor function receives a cancel function as a parameter
    cancel = c;
  )
);
// cancel the request
cancel();

这里推荐看GitHub或axios的官网,中文网有些滞后,有的内容不全。不过大家根据自己喜好去查阅~

以上是关于前端热门技术——axios详细讲解的主要内容,如果未能解决你的问题,请参考以下文章

前端热门技术axios详细讲解——基本使用方法

前端热门技术axios详细讲解——拦截器

前端热门技术axios详细讲解——拦截器

前端杂文 axios的AxiosResponse分析

Echart图表在项目中如何使用?(前后端详细技术讲解)

Echart图表在项目中如何使用?(前后端详细技术讲解)