PCancelable.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. /**
  2. * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
  3. *
  4. * This source code is licensed under the MIT license found in the
  5. * LICENSE file in the root directory of this source tree.
  6. */
  7. 'use strict';
  8. var Symbol = global['jest-symbol-do-not-touch'] || global.Symbol;
  9. var Symbol = global['jest-symbol-do-not-touch'] || global.Symbol;
  10. var Promise = global[Symbol.for('jest-native-promise')] || global.Promise;
  11. class CancelError extends Error {
  12. constructor() {
  13. super('Promise was canceled');
  14. this.name = 'CancelError';
  15. }
  16. }
  17. class PCancelable {
  18. static fn(fn) {
  19. return function() {
  20. const args = [].slice.apply(arguments);
  21. return new PCancelable((onCancel, resolve, reject) => {
  22. args.unshift(onCancel);
  23. fn.apply(null, args).then(resolve, reject);
  24. });
  25. };
  26. }
  27. constructor(executor) {
  28. this._pending = true;
  29. this._canceled = false;
  30. this._promise = new Promise((resolve, reject) => {
  31. this._reject = reject;
  32. return executor(
  33. fn => {
  34. this._cancel = fn;
  35. },
  36. val => {
  37. this._pending = false;
  38. resolve(val);
  39. },
  40. err => {
  41. this._pending = false;
  42. reject(err);
  43. }
  44. );
  45. });
  46. }
  47. then() {
  48. return this._promise.then.apply(this._promise, arguments);
  49. }
  50. catch() {
  51. return this._promise.catch.apply(this._promise, arguments);
  52. }
  53. cancel() {
  54. if (!this._pending || this._canceled) {
  55. return;
  56. }
  57. if (typeof this._cancel === 'function') {
  58. try {
  59. this._cancel();
  60. } catch (err) {
  61. this._reject(err);
  62. }
  63. }
  64. this._canceled = true;
  65. this._reject(new CancelError());
  66. }
  67. get canceled() {
  68. return this._canceled;
  69. }
  70. }
  71. Object.setPrototypeOf(PCancelable.prototype, Promise.prototype);
  72. module.exports = PCancelable;
  73. module.exports.CancelError = CancelError;