Deferred.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. "use strict";
  2. /**
  3. * Copyright 2022 Google LLC.
  4. * Copyright (c) Microsoft Corporation.
  5. *
  6. * Licensed under the Apache License, Version 2.0 (the "License");
  7. * you may not use this file except in compliance with the License.
  8. * You may obtain a copy of the License at
  9. *
  10. * http://www.apache.org/licenses/LICENSE-2.0
  11. *
  12. * Unless required by applicable law or agreed to in writing, software
  13. * distributed under the License is distributed on an "AS IS" BASIS,
  14. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15. * See the License for the specific language governing permissions and
  16. * limitations under the License.
  17. */
  18. Object.defineProperty(exports, "__esModule", { value: true });
  19. exports.Deferred = void 0;
  20. class Deferred {
  21. #isFinished = false;
  22. #promise;
  23. #resolve;
  24. #reject;
  25. get isFinished() {
  26. return this.#isFinished;
  27. }
  28. constructor() {
  29. this.#promise = new Promise((resolve, reject) => {
  30. this.#resolve = resolve;
  31. this.#reject = reject;
  32. });
  33. // Needed to avoid `Uncaught (in promise)`. The promises returned by `then`
  34. // and `catch` will be rejected anyway.
  35. this.#promise.catch((_error) => {
  36. // Intentionally empty.
  37. });
  38. }
  39. then(onFulfilled, onRejected) {
  40. return this.#promise.then(onFulfilled, onRejected);
  41. }
  42. catch(onRejected) {
  43. return this.#promise.catch(onRejected);
  44. }
  45. resolve(value) {
  46. if (!this.#isFinished) {
  47. this.#isFinished = true;
  48. this.#resolve(value);
  49. }
  50. }
  51. reject(reason) {
  52. if (!this.#isFinished) {
  53. this.#isFinished = true;
  54. this.#reject(reason);
  55. }
  56. }
  57. finally(onFinally) {
  58. return this.#promise.finally(onFinally);
  59. }
  60. [Symbol.toStringTag] = 'Promise';
  61. }
  62. exports.Deferred = Deferred;
  63. //# sourceMappingURL=Deferred.js.map