Skip to content

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 machines have four built-in states:

  1. Idle - The initial state before the promise is executed
  2. Pending - The promise is in flight (contains promise and params)
  3. Resolved - The promise completed successfully (contains result)
  4. Rejected - The promise failed (contains error)

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);

Call the execute method with parameters and await the result:

// Trigger addition and await result
await adder.execute(2, 3);
// Alternative: Await promise from state (if currently pending)
const state = adder.getState();
if (state.is("Pending")) await state.data.promise;

Access the current state with type-safe properties:

const state = adder.getState();
// Pattern match on state for messaging
const message = adder.getState().match({
Idle: () => "Ready to add.",
Pending: (params) => `Adding: ${params}`,
Resolved: (result) => `Result: ${result}`,
Rejected: (error) => `Error: ${error}`,
});

Now that you understand Promise Machines, explore these related guides: