关于javascript:axios源码五

3次阅读

共计 1438 个字符,预计需要花费 4 分钟才能阅读完成。

今日来看一下 axios 的拦截器, 这样在之后的外围 Axios 构造函数中就更容易了解了.
拦截器也是一个构造函数, 而后在原型 prototype 上加了三个办法, 别离是 use, eject, forEach
use 办法是增加拦截器的,eject 是移除拦截器的,forEach 则是迭代拦截器. 具体请看 https://www.kancloud.cn/yunye… 搜寻 ” 拦截器 ” 即可

'use strict';

var utils = require('./../utils');

function InterceptorManager() {this.handlers = [];
}

/**
 * Add a new interceptor to the stack
 * 
 * 在栈中增加一个新的拦截器
 *
 * @param {Function} fulfilled The function to handle `then` for a `Promise`   解决 then 办法的函数
 * @param {Function} rejected The function to handle `reject` for a `Promise`  解决 reject 办法的函数
 *
 * @return {Number} An ID used to remove interceptor later  用来移除拦截器的 id
 */
InterceptorManager.prototype.use = function use(fulfilled, rejected, options) {
  this.handlers.push({
    fulfilled: fulfilled,
    rejected: rejected,
    synchronous: options ? options.synchronous : false,
    runWhen: options ? options.runWhen : null
  });
  return this.handlers.length - 1;
};

/**
 * Remove an interceptor from the stack
 * 
 * 从栈中移除拦截器
 *
 * @param {Number} id The ID that was returned by `use`  下面的 use 办法返回的 id
 */
InterceptorManager.prototype.eject = function eject(id) {if (this.handlers[id]) {this.handlers[id] = null;
  }
};

/**
 * Iterate over all the registered interceptors  迭代所有注册的拦截器
 *
 * This method is particularly useful for skipping over any
 * interceptors that may have become `null` calling `eject`.
 *
 * 这个办法在跳过曾经是 null 的拦截器时, 特地有用
 * 
 * @param {Function} fn The function to call for each interceptor  每个拦截器都被调用的函数
 */
InterceptorManager.prototype.forEach = function forEach(fn) {utils.forEach(this.handlers, function forEachHandler(h) {// utils 文件中的 forEach 办法, 参考 axios 源码 ( 三)
    if (h !== null) {fn(h);
    }
  });
};

module.exports = InterceptorManager;
正文完
 0