Axios 是一个基于 Promise 的 HTTP 客户端,同时支持浏览器和 Node.js 环境。它是一个优秀的 HTTP 客户端,被普遍地应用在大量的 Web 项目中。具体介绍可见官方文档javascript
对于大多数应用来讲,都会遇到要统一处理ajax请求的场景,为了较好地解决这个问题,拦截器就应运而生了。
在Axios中它提供了请求拦截器和响应拦截器来分别处理请求和响应,它们的做用以下:java
接下来,本文将经过axios源码来阐述拦截器是如何设计实现的。ios
首先如下面的代码为例,经过use将方法注册到拦截器中git
// request interceptor axios.interceptors.request.use( config => { console.log('config', config); return config; }, err => Promise.reject(err), ); // response interceptor axios.interceptors.response.use(response => { console.log('response', response); return response; }); // axios/lib/core/InterceptorManager.js // 在拦截器管理类中经过use方法向任务列表中添加任务 InterceptorManager.prototype.use = function use(fulfilled, rejected) { this.handlers.push({ fulfilled: fulfilled, rejected: rejected }); return this.handlers.length - 1; };
// 先看lib/axios.js(入口文件) 中的建立实例的方法 function createInstance(defaultConfig) { var context = new Axios(defaultConfig); // REVIEW[epic=interceptors,seq=0] 在axios对象上绑定request方法,使得axios({option})这样的方式便可调用request方法 var instance = bind(Axios.prototype.request, context); // Copy axios.prototype to instance utils.extend(instance, Axios.prototype, context); // Copy context to instance utils.extend(instance, context); return instance; } // 重点在于Axios.prototype.request Axios.prototype.request = function request(config) { // ...已省略部分代码 // Hook up interceptors middleware // REVIEW[epic=interceptors,seq=2] dispatchRequest 为咱们使用axios时,项目中调用的请求 var chain = [dispatchRequest, undefined]; var promise = Promise.resolve(config); // REVIEW[epic=interceptors,seq=4] 向拦截器任务列表的头部注册 request任务 this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) { chain.unshift(interceptor.fulfilled, interceptor.rejected); }); // REVIEW[epic=interceptors,seq=5] 向拦截器任务列表的尾部注册 response任务 this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) { chain.push(interceptor.fulfilled, interceptor.rejected); }); // 经过上面的注册方式,咱们能够知道最后的chain数组会长成的样子是: // [ ...requestInterceptor, dispatchRequest,undefined, ...responseInterceptor ] // 这样就保证了拦截器执行的顺序 while (chain.length) { // 由于是成对注册的任务(fulfilled, rejected)因此执行的时候也是shift2次 promise = promise.then(chain.shift(), chain.shift()); } return promise; };
能够看出经过从不一样的位置向任务列表中添加任务,实现了任务的编排,达到了按requestInterceptor => Request => responseInterceptor 顺序执行的目的github
任务的调度主要是看上面 request函数中的这一行ajax
var promise = Promise.resolve(config); while (chain.length) { // 由于是成对注册的任务(fulfilled, rejected)因此执行的时候也是shift2次 promise = promise.then(chain.shift(), chain.shift()); }
能够看出就是按注册的顺序依次执行,而且每一个任务中都须要返回config。axios
在此次的源码阅读时,明显感受到,由于以前几回的积累,读源码这件事开始变得没有那么的“困难”了。可是在写文档的时候如何更清晰地表达,仍是遇到了点问题。所以借鉴了下网上已有的文档,使用了任务注册 => 任务编排 => 任务调度,以任务为视角来作解析的方式来阐述代码。数组