You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

57 lines
1.2 KiB

  1. 'use strict';
  2. var Cancel = require('./Cancel');
  3. /**
  4. * A `CancelToken` is an object that can be used to request cancellation of an operation.
  5. *
  6. * @class
  7. * @param {Function} executor The executor function.
  8. */
  9. function CancelToken(executor) {
  10. if (typeof executor !== 'function') {
  11. throw new TypeError('executor must be a function.');
  12. }
  13. var resolvePromise;
  14. this.promise = new Promise(function promiseExecutor(resolve) {
  15. resolvePromise = resolve;
  16. });
  17. var token = this;
  18. executor(function cancel(message) {
  19. if (token.reason) {
  20. // Cancellation has already been requested
  21. return;
  22. }
  23. token.reason = new Cancel(message);
  24. resolvePromise(token.reason);
  25. });
  26. }
  27. /**
  28. * Throws a `Cancel` if cancellation has been requested.
  29. */
  30. CancelToken.prototype.throwIfRequested = function throwIfRequested() {
  31. if (this.reason) {
  32. throw this.reason;
  33. }
  34. };
  35. /**
  36. * Returns an object that contains a new `CancelToken` and a function that, when called,
  37. * cancels the `CancelToken`.
  38. */
  39. CancelToken.source = function source() {
  40. var cancel;
  41. var token = new CancelToken(function executor(c) {
  42. cancel = c;
  43. });
  44. return {
  45. token: token,
  46. cancel: cancel
  47. };
  48. };
  49. module.exports = CancelToken;