javascript / expert
Snippet
Generator-Gesteuerte Zustandsmaschine für Mehrstufigen Transaktionsablauf in Next.js Server Actions
Dieses Snippet implementiert eine generatorgesteuerte Zustandsmaschine (FSM), um komplexe mehrstufige Transaktionsabläufe in Next.js Server Actions zu orchestrieren. Durch die Verwendung von yield zur Unterbrechung der Ausführung und Rückgabe des Schrittzustands bleibt der Ausführungsablauf strikt linear und gut testbar.
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
Erklärung
1
export function* createCheckoutWorkflow(cartItems) {
Deklariert eine Generator-Funktion als deterministische Zustandsmaschine.
2
const validated = yield { step: 'VALIDATING', items: cartItems };
Pausiert die Ausführung, gibt den Schrittzustand aus und wartet auf Ergebnisse via .next(payload).
3
next = workflow.next(validRes);
Setzt die Generatorausführung fort und übergibt die Validierungsergebnisse.