Deferred.js 952 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. "use strict";
  2. /**
  3. * This is apparently a bit like a Jquery deferred, hence the name
  4. */
  5. class Deferred {
  6. constructor(Promise) {
  7. this._state = Deferred.PENDING;
  8. this._resolve = undefined;
  9. this._reject = undefined;
  10. this._promise = new Promise((resolve, reject) => {
  11. this._resolve = resolve;
  12. this._reject = reject;
  13. });
  14. }
  15. get state() {
  16. return this._state;
  17. }
  18. get promise() {
  19. return this._promise;
  20. }
  21. reject(reason) {
  22. if (this._state !== Deferred.PENDING) {
  23. return;
  24. }
  25. this._state = Deferred.REJECTED;
  26. this._reject(reason);
  27. }
  28. resolve(value) {
  29. if (this._state !== Deferred.PENDING) {
  30. return;
  31. }
  32. this._state = Deferred.FULFILLED;
  33. this._resolve(value);
  34. }
  35. }
  36. // TODO: should these really live here? or be a seperate 'state' enum
  37. Deferred.PENDING = "PENDING";
  38. Deferred.FULFILLED = "FULFILLED";
  39. Deferred.REJECTED = "REJECTED";
  40. module.exports = Deferred;