lazy.js 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. /*---------------------------------------------------------------------------------------------
  2. * Copyright (c) Microsoft Corporation. All rights reserved.
  3. * Licensed under the MIT License. See License.txt in the project root for license information.
  4. *--------------------------------------------------------------------------------------------*/
  5. export class Lazy {
  6. constructor(executor) {
  7. this.executor = executor;
  8. this._didRun = false;
  9. }
  10. /**
  11. * Get the wrapped value.
  12. *
  13. * This will force evaluation of the lazy value if it has not been resolved yet. Lazy values are only
  14. * resolved once. `getValue` will re-throw exceptions that are hit while resolving the value
  15. */
  16. getValue() {
  17. if (!this._didRun) {
  18. try {
  19. this._value = this.executor();
  20. }
  21. catch (err) {
  22. this._error = err;
  23. }
  24. finally {
  25. this._didRun = true;
  26. }
  27. }
  28. if (this._error) {
  29. throw this._error;
  30. }
  31. return this._value;
  32. }
  33. /**
  34. * Get the wrapped value without forcing evaluation.
  35. */
  36. get rawValue() { return this._value; }
  37. }