Skip to content

Async Calculator

This example demonstrates a basic promise machine for handling asynchronous calculations:

  • Defines a promise machine with Idle, Pending, Resolved, and Rejected states
  • Manages async operation lifecycle automatically
  • Provides type-safe event parameters and state payloads
  • Shows how promise machines handle success and error cases

The promise machine pattern is perfect for any asynchronous operation - from simple calculations to complex API workflows.

import { createPromiseMachine, withReset } from "matchina";
export function createAsyncCalculatorMachine() {
const baseMachine = createPromiseMachine(
(a: number, b: number) =>
new Promise<number>((resolve) => setTimeout(() => resolve(a + b), 1000))
);
return withReset(baseMachine, baseMachine.states.Idle());
}
export type AsyncCalculatorMachine = ReturnType<
typeof createAsyncCalculatorMachine
>;