Source: lib/util/operation_manager.js

  1. /**
  2. * @license
  3. * Copyright 2016 Google Inc.
  4. *
  5. * Licensed under the Apache License, Version 2.0 (the "License");
  6. * you may not use this file except in compliance with the License.
  7. * You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. */
  17. goog.provide('shaka.util.OperationManager');
  18. goog.require('shaka.util.ArrayUtils');
  19. goog.require('shaka.util.IDestroyable');
  20. /**
  21. * A utility for cleaning up AbortableOperations, to help simplify common
  22. * patterns and reduce code duplication.
  23. *
  24. * @implements {shaka.util.IDestroyable}
  25. */
  26. shaka.util.OperationManager = class {
  27. constructor() {
  28. /** @private {!Array.<!shaka.extern.IAbortableOperation>} */
  29. this.operations_ = [];
  30. }
  31. /**
  32. * Manage an operation. This means aborting it on destroy() and removing it
  33. * from the management set when it complete.
  34. *
  35. * @param {!shaka.extern.IAbortableOperation} operation
  36. */
  37. manage(operation) {
  38. this.operations_.push(operation.finally(() => {
  39. shaka.util.ArrayUtils.remove(this.operations_, operation);
  40. }));
  41. }
  42. /** @override */
  43. destroy() {
  44. let cleanup = [];
  45. this.operations_.forEach((op) => {
  46. // Catch and ignore any failures. This silences error logs in the
  47. // JavaScript console about uncaught Promise failures.
  48. op.promise.catch(() => {});
  49. // Now abort the operation.
  50. cleanup.push(op.abort());
  51. });
  52. this.operations_ = [];
  53. return Promise.all(cleanup);
  54. }
  55. };