Ohm-Management - Projektarbeit B-ME
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

AsyncAction.js 2.3KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. import { Action } from './Action';
  2. export class AsyncAction extends Action {
  3. constructor(scheduler, work) {
  4. super(scheduler, work);
  5. this.scheduler = scheduler;
  6. this.work = work;
  7. this.pending = false;
  8. }
  9. schedule(state, delay = 0) {
  10. if (this.closed) {
  11. return this;
  12. }
  13. this.state = state;
  14. const id = this.id;
  15. const scheduler = this.scheduler;
  16. if (id != null) {
  17. this.id = this.recycleAsyncId(scheduler, id, delay);
  18. }
  19. this.pending = true;
  20. this.delay = delay;
  21. this.id = this.id || this.requestAsyncId(scheduler, this.id, delay);
  22. return this;
  23. }
  24. requestAsyncId(scheduler, id, delay = 0) {
  25. return setInterval(scheduler.flush.bind(scheduler, this), delay);
  26. }
  27. recycleAsyncId(scheduler, id, delay = 0) {
  28. if (delay !== null && this.delay === delay && this.pending === false) {
  29. return id;
  30. }
  31. clearInterval(id);
  32. }
  33. execute(state, delay) {
  34. if (this.closed) {
  35. return new Error('executing a cancelled action');
  36. }
  37. this.pending = false;
  38. const error = this._execute(state, delay);
  39. if (error) {
  40. return error;
  41. }
  42. else if (this.pending === false && this.id != null) {
  43. this.id = this.recycleAsyncId(this.scheduler, this.id, null);
  44. }
  45. }
  46. _execute(state, delay) {
  47. let errored = false;
  48. let errorValue = undefined;
  49. try {
  50. this.work(state);
  51. }
  52. catch (e) {
  53. errored = true;
  54. errorValue = !!e && e || new Error(e);
  55. }
  56. if (errored) {
  57. this.unsubscribe();
  58. return errorValue;
  59. }
  60. }
  61. _unsubscribe() {
  62. const id = this.id;
  63. const scheduler = this.scheduler;
  64. const actions = scheduler.actions;
  65. const index = actions.indexOf(this);
  66. this.work = null;
  67. this.state = null;
  68. this.pending = false;
  69. this.scheduler = null;
  70. if (index !== -1) {
  71. actions.splice(index, 1);
  72. }
  73. if (id != null) {
  74. this.id = this.recycleAsyncId(scheduler, id, null);
  75. }
  76. this.delay = null;
  77. }
  78. }
  79. //# sourceMappingURL=AsyncAction.js.map