axios - 7 - 注入器
Axios 支持请求以及响应的注入,具体是如何实现的呢?又有什么样的技巧被使用?
console.info
该系类文章旨在研究 axios 的实现 。在研究源码的基础上,去理解 axios 是如何实现 ajax 请求并更好的去使用这个库。
简介
对应文件为 lib/core/InterceptorManager.js。
这个类主要用于存放一个对象,如下
{
    fulfilled: fulfilled,
    rejected: rejected
}
fulfilled:为 promise 执行 then 时的第一个参数;fulfilled:为 promise 执行 then 时的第二个参数;
也就是说,该类存在的意义是为了不断的 then 方法调用。
代码分析
实例化对象函数
function InterceptorManager() {
  this.handlers = [];
}
handlers 即为实例化对象时,内部保存 fulfilled/rejected 的数组。
对象下的方法
use
InterceptorManager.prototype.use = function use(fulfilled, rejected) {
    this.handlers.push({
        fulfilled: fulfilled,
        rejected: rejected
    });
    return this.handlers.length - 1;
};
用于添加 fulfilled/rejected 对象,添加完成后返回该对象对应唯一的 id 。
eject
InterceptorManager.prototype.eject = function eject(id) {
    if (this.handlers[id]) {
        this.handlers[id] = null;
    }
};
根据添加时返回的 id,去除对应 fulfilled/rejected 对象,这里的去除仅仅是将 handlers 中对应 id 的一项置空。
forEach
InterceptorManager.prototype.forEach = function forEach(fn) {
    utils.forEach(this.handlers, function forEachHandler(h) {
        // 去除的 fulfilled/rejected 对像会为置空,不需要遍历
        if (h !== null) {
            fn(h);
        }
    });
};
将该对象内每一个 fulfilled/rejected 对象作为参数传入 fn 中,并执行 fn 函数。
总结
该类将需要执行的 Promise 链的信息都保存下来,方便调用。