axios拦截器执行流程分析

问题:平时我们发送axios请求可能会有请求拦截或者响应拦截,但是我们axios请求拦截和响应拦截的执行顺是不一致的。

axios拦截器的执行顺序

1.请求拦截:axios的请求拦截会先执行最后指定的回调函数先执行,依次向前面执行。
2.响应拦截:axios的响应拦截会先执行最先指定的回调函数先执行,依次向后面执行
以下列代码为例

    
        axios.interceptors.request.use(config => {
            console.log(`请求拦截1`);
            return config;
        });
        axios.interceptors.request.use(config => {
            // 在发送请求之前做些什么
            console.log(`请求拦截2`);
            return config;
        });
 
        // 添加响应拦截器
        axios.interceptors.response.use(response => {
            // 对响应数据做点什么
            console.log(`成功的响应拦截1`);
            return response.data;
        });

        // 添加响应拦截器
        axios.interceptors.response.use(response => {
            // 对响应数据做点什么
            console.log(`成功的响应拦截2`);
            return response;
       });
        
        // 发送请求
        axios.get('/posts')
            .then(response => {
                console.log('成功了');
            })

以上代码的打印结果顺序为:
1.console.log(请求拦截2);
2.console.log(请求拦截1);
3.console.log(成功的响应拦截1);
4.console.log(成功的响应拦截2);
5.console.log(成功了);

为什么请求拦截2会在请求拦截1前面执行呢?
因为axios将响应拦截和请求拦截都存放在一个数组中

/*创建用于保存请求/响应拦截函数的数组
数组的中间放发送请求的函数
数组的左边放请求拦截器函数(成功/失败)
数组的右边放响应拦截器函数*/
var chain = [dispatchRequest,undefined];
//后添加的请求拦截器保存在数组的前面
this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) {
chain.unshift(interceptor.fulfilled,interceptor.rejected);
});
//后添加的响应拦截器保存在数组的后面
this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) {
chain.push(interceptor.fulfilled,interceptor.rejected);
});

而axios开始发送请求,是每次从数组中删除两个回调函数来开始执行,只到数组为空则执行完成。

//通过promise的then()串连起所有的请求拦截器/请求方法/响应拦截器
while (chain.length) {
promise = promise.then(chain.shift(), chain.shift());
}

axios的请求拦截是向数组前面追加的,而响应拦截是向数组后面追加的,所以当axios发送请求时,
请求拦截的回调函数最后指定的,最先被调用,从左向右执行。如下图所示:
顺序图片
以上就是axios发送请求关于请求拦截和响应拦截的执行过程,觉得有用的话点个赞吧!

  • 5
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值