lazy.js 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  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. * True if the lazy value has been resolved.
  12. */
  13. hasValue() { return this._didRun; }
  14. /**
  15. * Get the wrapped value.
  16. *
  17. * This will force evaluation of the lazy value if it has not been resolved yet. Lazy values are only
  18. * resolved once. `getValue` will re-throw exceptions that are hit while resolving the value
  19. */
  20. getValue() {
  21. if (!this._didRun) {
  22. try {
  23. this._value = this.executor();
  24. }
  25. catch (err) {
  26. this._error = err;
  27. }
  28. finally {
  29. this._didRun = true;
  30. }
  31. }
  32. if (this._error) {
  33. throw this._error;
  34. }
  35. return this._value;
  36. }
  37. /**
  38. * Get the wrapped value without forcing evaluation.
  39. */
  40. get rawValue() { return this._value; }
  41. }