queue.js 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. import { __awaiter } from "tslib";
  2. class Queue {
  3. constructor() {
  4. this.status = "waiting";
  5. }
  6. append(item, autoRun = false) {
  7. const node = new Node(item);
  8. if (!this.current || !this.end) {
  9. this.current = this.end = node;
  10. }
  11. else {
  12. this.end.setNext(node);
  13. this.end = node;
  14. }
  15. if (autoRun) {
  16. this.startRun();
  17. }
  18. }
  19. startRun() {
  20. if (this.status === "waiting") {
  21. this.run();
  22. this._promise = new Promise((resolve) => {
  23. this._myResolve = resolve;
  24. });
  25. }
  26. return this._promise;
  27. }
  28. run() {
  29. return __awaiter(this, void 0, void 0, function* () {
  30. if (this.current) {
  31. this.status = "running";
  32. const current = this.current;
  33. const self = current.getSelf();
  34. this.current = this.current.getNext();
  35. const res = yield self.run();
  36. current.destroy();
  37. if (res === false) {
  38. this.status = "waiting";
  39. this._myResolve("stopped");
  40. this._promise = undefined;
  41. this._myResolve = undefined;
  42. }
  43. else {
  44. this.run();
  45. }
  46. }
  47. else {
  48. this.end = undefined;
  49. this.status = "waiting";
  50. this._myResolve("finished");
  51. this._promise = undefined;
  52. this._myResolve = undefined;
  53. }
  54. });
  55. }
  56. }
  57. class Node {
  58. constructor(self) {
  59. this.self = self;
  60. }
  61. getSelf() {
  62. return this.self;
  63. }
  64. setPrev(prev) {
  65. this.prev = prev;
  66. if (prev) {
  67. prev.next = this;
  68. }
  69. }
  70. setNext(next) {
  71. this.next = next;
  72. if (next) {
  73. next.prev = this;
  74. }
  75. }
  76. getPrev() {
  77. return this.prev;
  78. }
  79. getNext() {
  80. return this.next;
  81. }
  82. destroy() {
  83. if (this.prev) {
  84. this.prev.setNext(undefined);
  85. }
  86. if (this.next) {
  87. this.next.setPrev(undefined);
  88. }
  89. this.prev = undefined;
  90. this.next = undefined;
  91. this.self = undefined;
  92. }
  93. }
  94. export { Queue };