PromiseLogic.createFlipFlop()
The PromiseLogic.createFlipFlop() method creates a state trigger (FlipFlop), used to manage boolean state toggling. FlipFlop provides state toggling, state setting, and state query functions.
FlipFlop's design is inspired by flip-flops in digital circuits, it ensures atomicity and consistency of state changes, particularly suitable for async scenarios requiring state management.
Syntax
PromiseLogic.createFlipFlop(initialState?)
Parameters
| Parameter | Type | Description |
|---|---|---|
| initialState | boolean | Initial state, defaults to false |
Return Value
Returns a FlipFlop instance containing state management methods.
FlipFlopFlipFlop Instance Methods
getState()
Get current state.
const currentState = flipFlop.getState();
// Returns: boolean
setState(state)
Set specific state.
await flipFlop.setState(true);
// Returns: Promise<void>
toggle()
Toggle state (true ↔ false).
await flipFlop.toggle();
// Returns: Promise<void>
Behavior
Creation Successful
Successfully creates a FlipFlop instance containing state management methods.
Special Case
The createFlipFlop method never fails, always returns a valid FlipFlop instance.
Examples
Basic Usage
Create and use FlipFlop state trigger
State Synchronization
Ensure consistency of state changes
Real Application
Implement switch control using FlipFlop
Advanced Application
Build state machine pattern
Important Notes
- • FlipFlop is a state trigger used to manage boolean state toggling
- • All state change operations are asynchronous, ensuring state consistency
- • Can be used to build simple state machines, switch controls, mode switching, etc.
- • FlipFlop instances are thread-safe and can be safely used in multiple async operations
- • State change operations return Promise, can wait for state change completion