javascript / expert
Snippet
Generator-Driven Finite State Machine for Multi-Step Transactional Control Flow in Next.js Server Actions
This snippet implements a generator-driven Finite State Machine (FSM) to orchestrate complex multi-step transactional control flows inside Next.js Server Actions. Using yield to pause execution and yield state targets while accepting step resolution inputs back via .next(payload), execution steps remain strictly linear and easily testable.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
export function* createCheckoutWorkflow(cartItems) {const validated = yield { step: 'VALIDATING', items: cartItems };if (!validated.success) return { status: 'FAILED_VALIDATION' };const charged = yield { step: 'CHARGING', amount: validated.total };if (!charged.success) return { status: 'FAILED_PAYMENT' };return { status: 'COMPLETED', orderId: charged.txId };}export async function processOrderAction(cartItems) {'use server';const workflow = createCheckoutWorkflow(cartItems);let next = workflow.next();const validRes = { success: true, total: 99.99 };next = workflow.next(validRes);const payRes = { success: true, txId: 'tx_9981' };const finalResult = workflow.next(payRes);return finalResult.value;}
nextjs
Breakdown
1
export function* createCheckoutWorkflow(cartItems) {
Declares a generator function acting as a deterministic state machine controller.
2
const validated = yield { step: 'VALIDATING', items: cartItems };
Pauses execution, yields state output, and waits for step injection via .next(payload).
3
next = workflow.next(validRes);
Resumes generator execution, passing back step validation results.