state-handler.ts 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. export class StateHandler {
  2. private condition: boolean = false;
  3. private rejectCondition: (() => void) | null = null;
  4. private resolveCondition: (() => void) | null = null;
  5. // 清理 resolve/reject 函数
  6. private clearPromises() {
  7. this.resolveCondition = null;
  8. this.rejectCondition = null;
  9. }
  10. isConditionTrue(): boolean {
  11. return this.condition;
  12. }
  13. reset() {
  14. this.condition = false;
  15. this.clearPromises();
  16. }
  17. // 触发状态为 false 时,reject
  18. setConditionFalse() {
  19. this.condition = false;
  20. if (this.rejectCondition) {
  21. this.rejectCondition();
  22. this.clearPromises();
  23. }
  24. }
  25. // 触发状态为 true 时,resolve
  26. setConditionTrue() {
  27. this.condition = true;
  28. if (this.resolveCondition) {
  29. this.resolveCondition();
  30. this.clearPromises();
  31. }
  32. }
  33. // 返回一个 Promise,等待 condition 变为 true
  34. waitForCondition(): Promise<void> {
  35. return new Promise((resolve, reject) => {
  36. if (this.condition) {
  37. resolve(); // 如果 condition 已经为 true,立即 resolve
  38. } else {
  39. this.resolveCondition = resolve;
  40. this.rejectCondition = reject;
  41. }
  42. });
  43. }
  44. }