javascript / expert
Snippet
Async State Machine Orchestration using Generator Functions
Combining JavaScript Generator functions with Vue reactive primitives enables explicit, step-by-step async state machine workflows without callback spaghetti or uncontrolled reactive state mutations.
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
24
25
26
27
28
29
import { ref, readonly } from 'vue';export function useAsyncWorkflow(stepGeneratorFn) {const currentState = ref('idle');const isProcessing = ref(false);let iterator = null;const start = async (...args) => {iterator = stepGeneratorFn(...args);return next();};const next = async (payload) => {isProcessing.value = true;try {const { value, done } = await iterator.next(payload);if (done) {currentState.value = 'completed';} else {currentState.value = value.stateName;}return value;} finally {isProcessing.value = false;}};return { state: readonly(currentState), isProcessing, start, next };}
vue
Breakdown
1
iterator = stepGeneratorFn(...args);
Instantiates the state generator yielding discrete workflow stages.
2
const { value, done } = await iterator.next(payload);
Advances the generator asynchronously passing dynamic context payload to the current yield block.
3
return { state: readonly(currentState), isProcessing, start, next };
Exposes read-only state controls to enforce unidirectional flow architecture.