功能点

名称 功能点
cancel.js Cancel的信息封装
cancelToken.js 执行取消操作,并返回对应的取消结果
isCancel.js 判断取消的状态

isCancel源码

  1. 'use strict';
  2. // 判断cancel的状态
  3. export default function isCancel(value) {
  4. return !!(value && value.__CANCEL__);
  5. }

cancel源码

  1. 'use strict';
  2. /**
  3. * 当执行 “取消请求” 操作时会抛出 Cancel 对象作为异常
  4. * @class
  5. * @param {string=} message The message.
  6. */
  7. // 初始化Cancel Function对象
  8. function Cancel(message) {
  9. this.message = message;
  10. }
  11. // 在Cancel.prototype定一个对象toString, 用来返回一个字符串
  12. Cancel.prototype.toString = function toString() {
  13. return this.message ? `Cancel: ${this.message}` : 'Cancel';
  14. };
  15. // 定一个当前cancel的状态 _CANCEL_ = true;
  16. Cancel.prototype.__CANCEL__ = true;
  17. export default Cancel;

cancelToken源码

  1. 'use strict';
  2. import Cancel from './cancel';
  3. /**
  4. * 通过 CancelToken 来取消请求操作
  5. *
  6. * @class
  7. * @param {Function} executor The executor function.
  8. */
  9. function CancelToken(executor) {
  10. // 如果executor不是function,则类型错误
  11. if (typeof executor !== 'function') {
  12. throw new TypeError('executor must be a function.');
  13. }
  14. // 定义Promise
  15. var resolvePromise;
  16. // 定一个promise
  17. this.promise = new Promise(function promiseExecutor(resolve) {
  18. resolvePromise = resolve;
  19. });
  20. var token = this;
  21. executor(function cancel(message) {
  22. if (token.reason) {
  23. // 取消操作已被调用过
  24. return;
  25. }
  26. token.reason = new Cancel(message);
  27. resolvePromise(token.reason);
  28. });
  29. }
  30. /**
  31. * 如果请求已经取消,抛出 Cancel 异常
  32. */
  33. CancelToken.prototype.throwIfRequested = function throwIfRequested() {
  34. if (this.reason) {
  35. throw this.reason;
  36. }
  37. };
  38. /**
  39. * 通过 source 来返回 CancelToken 实例和取消 CancelToken 的函数
  40. */
  41. CancelToken.source = function source() {
  42. var cancel;
  43. var token = new CancelToken(function executor(c) {
  44. cancel = c;
  45. });
  46. return {
  47. token: token,
  48. cancel: cancel,
  49. };
  50. };
  51. export default CancelToken;