功能点
| 名称 |
功能点 |
| cancel.js |
Cancel的信息封装 |
| cancelToken.js |
执行取消操作,并返回对应的取消结果 |
| isCancel.js |
判断取消的状态 |
isCancel源码
'use strict';// 判断cancel的状态export default function isCancel(value) { return !!(value && value.__CANCEL__);}
cancel源码
'use strict';/** * 当执行 “取消请求” 操作时会抛出 Cancel 对象作为异常 * @class * @param {string=} message The message. */ // 初始化Cancel Function对象function Cancel(message) { this.message = message;}// 在Cancel.prototype定一个对象toString, 用来返回一个字符串Cancel.prototype.toString = function toString() { return this.message ? `Cancel: ${this.message}` : 'Cancel';};// 定一个当前cancel的状态 _CANCEL_ = true;Cancel.prototype.__CANCEL__ = true;export default Cancel;
cancelToken源码
'use strict';import Cancel from './cancel';/** * 通过 CancelToken 来取消请求操作 * * @class * @param {Function} executor The executor function. */function CancelToken(executor) { // 如果executor不是function,则类型错误 if (typeof executor !== 'function') { throw new TypeError('executor must be a function.'); } // 定义Promise var resolvePromise; // 定一个promise this.promise = new Promise(function promiseExecutor(resolve) { resolvePromise = resolve; }); var token = this; executor(function cancel(message) { if (token.reason) { // 取消操作已被调用过 return; } token.reason = new Cancel(message); resolvePromise(token.reason); });}/** * 如果请求已经取消,抛出 Cancel 异常 */CancelToken.prototype.throwIfRequested = function throwIfRequested() { if (this.reason) { throw this.reason; }};/** * 通过 source 来返回 CancelToken 实例和取消 CancelToken 的函数 */CancelToken.source = function source() { var cancel; var token = new CancelToken(function executor(c) { cancel = c; }); return { token: token, cancel: cancel, };};export default CancelToken;