Source: lib/util/public_promise.js

  1. /*! @license
  2. * Shaka Player
  3. * Copyright 2016 Google LLC
  4. * SPDX-License-Identifier: Apache-2.0
  5. */
  6. goog.provide('shaka.util.PublicPromise');
  7. /**
  8. * @summary
  9. * A utility to create Promises with convenient public resolve and reject
  10. * methods.
  11. *
  12. * @extends {Promise<T>}
  13. * @template T
  14. */
  15. shaka.util.PublicPromise = class {
  16. /**
  17. * @return {!Promise<T>}
  18. */
  19. constructor() {
  20. let resolvePromise;
  21. let rejectPromise;
  22. // Promise.call causes an error. It seems that inheriting from a native
  23. // Promise is not permitted by JavaScript interpreters.
  24. // The work-around is to construct a Promise object, modify it to look like
  25. // the compiler's picture of PublicPromise, then return it. The caller of
  26. // new PublicPromise will receive |promise| instead of |this|, and the
  27. // compiler will be aware of the additional properties |resolve| and
  28. // |reject|.
  29. const promise = new Promise(((resolve, reject) => {
  30. resolvePromise = resolve;
  31. rejectPromise = reject;
  32. }));
  33. // Now cast the Promise object to our subclass PublicPromise so that the
  34. // compiler will permit us to attach resolve() and reject() to it.
  35. const publicPromise = /** @type {shaka.util.PublicPromise} */(promise);
  36. publicPromise.resolve = resolvePromise;
  37. publicPromise.reject = rejectPromise;
  38. return publicPromise;
  39. }
  40. /** @param {T=} value */
  41. resolve(value) {}
  42. /** @param {*=} reason */
  43. reject(reason) {}
  44. };