Effect.ts: Absence as First-Class
Core Concepts • Lesson 5 of 51
5. Generator Syntax - Imperative Style
yield* makes async code look synchronous, but it's still describing absence
Code Example
const program = Effect.gen(function* () {
// "Get" these values (they don't exist yet)
const a = yield* Effect.succeed(5);
const b = yield* Effect.succeed(10);
// Transform them
const sum = a + b;
// Return result
return `Sum: ${sum}`;
});
// Still just a description!
// Nothing has run yet.
await Effect.runPromise(program);
// NOW it runs: "Sum: 15"
Interactive Example
const program = Effect.gen(function* () {
const a = yield* Effect.succeed(5);
const b = yield* Effect.succeed(10);
return "Sum: " + (a + b);
});
const result = await Effect.runPromise(program);
return 'Generator syntax result: ' + result + '\n\n- a = 5 (described)\n- b = 10 (described)\n- sum computed imperatively\n- Nothing executed until runPromise!';
Explanation
Generator syntax: describing unavailability imperatively.
yield* looks like it "gets" values, but it doesn't! It DESCRIBES getting unavailable values.
No assumptions made:
- 'a' doesn't exist yet (we describe getting it)
- 'b' doesn't exist yet (we describe getting it)
- 'sum' doesn't exist yet (we describe computing it)
The entire function is a DESCRIPTION of working with unavailable data. Nothing executes until runPromise. We're not making assumptions - we're typing unavailability in an imperative style.
Part 5 of 51 in the Effect.ts Absence Modeling series