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