cancel.js 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. function Cancel(message) {
  2. this.message = message;
  3. console.log('1 cancel')
  4. }
  5. Cancel.prototype.toString = function toString() {
  6. return 'Cancel' + (this.message ? ': ' + this.message : '');
  7. };
  8. Cancel.prototype.__CANCEL__ = true;
  9. function CancelToken(executor) {
  10. if (typeof executor !== 'function') {
  11. throw new TypeError('executor must be a function.');
  12. }
  13. //console.log('2 CancelToken')
  14. var resolvePromise;
  15. this.promise = new Promise(function promiseExecutor(resolve) {
  16. resolvePromise = resolve;
  17. //console.log('3 CancelToken')
  18. });
  19. var token = this;
  20. executor(function cancel(message) {
  21. //console.log('4 CancelToken')
  22. if (token.reason) {
  23. // Cancellation has already been requested
  24. return;
  25. }
  26. //console.log('5 CancelToken')
  27. token.reason = new Cancel(message);
  28. resolvePromise(token.reason);
  29. });
  30. }
  31. /**
  32. * Throws a `Cancel` if cancellation has been requested.
  33. */
  34. CancelToken.prototype.throwIfRequested = function throwIfRequested() {
  35. //console.log('6 CancelToken')
  36. if (this.reason) {
  37. throw this.reason;
  38. }
  39. };
  40. /**
  41. * Returns an object that contains a new `CancelToken` and a function that, when called,
  42. * cancels the `CancelToken`.
  43. */
  44. CancelToken.source = function source() {
  45. var cancel;
  46. console.log('7 CancelToken')
  47. var token = new CancelToken(function executor(c) {
  48. cancel = c;
  49. });
  50. return {
  51. token: token,
  52. cancel: cancel
  53. };
  54. };
  55. function isCancel(value) {
  56. console.log('8 isCancel')
  57. return !!(value && value.__CANCEL__);
  58. };
  59. export {CancelToken,Cancel,isCancel}