A program is a valueLesson 2 of 23

How do you say "then"?

Put descriptions in order and use one step's result in the next.

andThen put two descriptions in a row. Real work has more steps than two, and each step usually needs what the one before it produced: first the user, then that user's posts.

Predict

Read main.ts. load has four lines of steps, and two of them log something. program is one log line. When you run the file, which lines print?

Check your answer

Only Nothing loaded.

Effect.gen(function*() { ... }) looks like code that is running, but it's lesson 1 again. It builds a description and hands it to you as a value. Nobody ran load, so none of its steps happened. Press Run and check.

Try it

  1. Change the last line to export const program = load. Before you run: in what order do the lines print, and about how far apart? The output shows when each line was printed.

  2. Inside load, getUser(1) appears after a yield*. Suppose you wrote const user = getUser(1) without it. What would user be?

  3. After the second log, add const posts = yield* getPosts(user) and log how many there are. Where does getPosts get its user from?

  4. Return { name: user.name, posts } instead of the name. Before you run: how long does the whole program take now?

About step 2

A description of fetching a user, not a user. getUser(1) only says what to do. yield* is how one step says "run this, wait for it, and give me what it produced". That is why user.name works on the next line.

What you found

Inside Effect.gen, each yield* is a "then". The steps run in the order you wrote them, each one can use the results of the earlier ones, and the value you return is what the whole thing produces. Two 300 millisecond calls take 600, because the second doesn't start until the first has answered.

It reads like ordinary code that runs top to bottom. It is still one value. load was built from getUser, getPosts and a few log lines, each a small description, and it can itself be a step in something larger. c.pipe(Effect.andThen(c)) from lesson 1 was the same idea in a shorter spelling.

So load is a thing you can hold. Suppose the server it talks to is unreliable, or slow. Do you have to open load up and rewrite its steps? Or can you change how it behaves without touching it?

02
Principle 2

Small descriptions make big ones

A program is built by combining smaller programs. Code written with Effect.gen reads top to bottom and is still one value.

OutputNot run yet

Not run yet

Read the code and say what it will do. Then press Run.