PromiseLogic.createFlipFlop()

Utility MethodCreate state trigger for managing boolean state toggling

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

javascript
PromiseLogic.createFlipFlop(initialState?)

Parameters

ParameterTypeDescription
initialStatebooleanInitial state, defaults to false

Return Value

Returns a FlipFlop instance containing state management methods.

FlipFlop

FlipFlop Instance Methods

getState()

Get current state.

javascript
const currentState = flipFlop.getState();
// Returns: boolean

setState(state)

Set specific state.

javascript
await flipFlop.setState(true);
// Returns: Promise<void>

toggle()

Toggle state (true ↔ false).

javascript
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

JAVASCRIPT
Loading...

State Synchronization

Ensure consistency of state changes

JAVASCRIPT
Loading...

Real Application

Implement switch control using FlipFlop

JAVASCRIPT
Loading...

Advanced Application

Build state machine pattern

JAVASCRIPT
Loading...

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