Promise Machines
What are Promise Machines?
Section titled “What are Promise Machines?”Promise Machines provide a type-safe way to manage asynchronous operations with state machines. They automatically track the lifecycle of promises, handling success and error cases with appropriate typing.
Promise Machine States
Section titled “Promise Machine States”Promise machines have four built-in states:
- Idle - The initial state before the promise is executed
- Pending - The promise is in flight (contains
promise
andparams
) - Resolved - The promise completed successfully (contains
result
) - Rejected - The promise failed (contains
error
)
Creating a Promise Machine
Section titled “Creating a Promise Machine”Create a promise machine by wrapping any async function:
const promiseToAdd = (a: number, b: number) => new Promise<number>((resolve) => setTimeout(() => resolve(a + b), 500));const adder = createPromiseMachine(promiseToAdd);
Using Promise Machines
Section titled “Using Promise Machines”1. Executing the Promise
Section titled “1. Executing the Promise”Call the execute
method with parameters and await the result:
// Trigger addition and await resultawait adder.execute(2, 3);
// Alternative: Await promise from state (if currently pending)const state = adder.getState();if (state.is("Pending")) await state.data.promise;
2. Checking State
Section titled “2. Checking State”Access the current state with type-safe properties:
const state = adder.getState();
// Pattern match on state for messagingconst message = adder.getState().match({ Idle: () => "Ready to add.", Pending: (params) => `Adding: ${params}`, Resolved: (result) => `Result: ${result}`, Rejected: (error) => `Error: ${error}`,});
Next Steps
Section titled “Next Steps”Now that you understand Promise Machines, explore these related guides:
- Lifecycle & Hooks - Add more advanced hooks for state changes
- Factory Machines - Create regular state machines
- React Integration - Use promise machines in React