javascript / expert
Snippet
Bidirectional Control Flow and State Injection with Generator Functions
Generator functions facilitate two-way communication between the caller and the function body. Beyond yielding intermediate states, generators receive external data when .next(value) is called, substituting the yield expression with that value. Callers can also inject runtime control exceptions into the generator body via .throw(error).
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
function* taskRunner(initialState) {try {const step1 = yield { status: 'PENDING', data: initialState };const step2 = yield { status: 'PROCESSING', data: step1.toUpperCase() };return { status: 'COMPLETED', result: step2 * 2 };} catch (error) {yield { status: 'FAILED', error: error.message };}}const gen = taskRunner('hello');console.log(gen.next().value);console.log(gen.next('world').value);console.log(gen.next(21).value);
nodejs
Breakdown
1
function* taskRunner(initialState)
Defines a generator function that pauses execution at each yield expression.
2
const step1 = yield { ... }
Pauses execution, emits the object, and assigns the argument from the subsequent .next(val) call to step1.
3
yield { status: 'FAILED', error: error.message }
Yields a recovery state if an error is injected into the generator via gen.throw().
4
gen.next('world')
Resumes the generator and passes 'world' back inside as the evaluation result of the first yield statement.