flatMap in Effect: Do This, Then That (Learning Effect, Part 3)

By Esteban Trillo2 min readupdated Learning EffectEffectTypeScript

The first step's value opens the next one. No value, no next step.
The first step's value opens the next one. No value, no next step.

A useful program rarely does one thing.

It parses an id. Then it fetches a user. Then it checks a permission. Then it writes something.

That is where flatMap shows up.

flatMap means:

If this Effect succeeds, use its value to choose the next Effect.

The plain version

Here is that chain with promises:

const getUser = async (input: string): Promise<User> => {
const id = parseUserId(input);
const user = await fetchUser(id);
return user;
};

It reads well.

Each line waits for the one above it.

The type says Promise<User>.

It does not say the id can be invalid. It does not say the user can be missing.

Both failures leave through throw. The caller finds out at runtime.

The caller also cannot tell which step failed without reading both functions.

With Effect, the chain looks almost the same. The difference is in the type.

A small chain

const parseUserId = (input: string) =>
Number.isInteger(Number(input))
? Effect.succeed(Number(input))
: Effect.fail(new InvalidUserId(input));
const fetchUser = (id: number) =>
id === 1
? Effect.succeed({ id, name: "Ada" })
: Effect.fail(new UserNotFound(id));
const program = parseUserId("1").pipe(Effect.flatMap((id) => fetchUser(id)));

The second step needs the value from the first step.

That is why this is flatMap.

Why does this use flatMap?

Failure skips the rest

If parseUserId("abc") fails, fetchUser does not run.

A flatMap chain with an early exitparseUserId turns the input into an id. flatMap hands that id to fetchUser, which turns it into a User. If parseUserId fails, the chain stops there with InvalidUserId and fetchUser never runs. If fetchUser fails, the chain ends with UserNotFound. Both failures land in the error slot.parseUserIdinput → idfetchUserid → UserUsersuccesserror slotInvalidUserIdUserNotFoundiduserfailsfails

That is the part I like.

The happy path reads straight down. The failure path stays in the type.

Effect.Effect<User, InvalidUserId | UserNotFound, never>;

The program can fail in either step.

If parseUserId fails, what happens to fetchUser?

The mistake: a callback that returns nothing

Braces change what an arrow function returns.

A one-line arrow returns its expression. A block body returns nothing unless you write return.

Effect code is full of arrows, so this comes up often.

parseUserId("1").pipe(
Effect.flatMap((id) => {
fetchUser(id);
}),
);

This builds a fetchUser Effect and drops it.

The callback returns void.

TypeScript catches this one. The error says void is not assignable to Effect.

When you see that message, look for a missing return.

The fix is one word.

Or drop the braces:

parseUserId("1").pipe(Effect.flatMap((id) => fetchUser(id)));

The part that finally clicked

This:

parseUserId("1").pipe(Effect.flatMap(fetchUser));

is the Effect version of:

const id = parseUserId("1");
const user = fetchUser(id);

Except the failures are not hiding.

They are part of the result.

Piwi hands a single letter to the user at a mailbox; a small note reads no noise.

Get the next one in your inbox

One email when a post goes out, with its sketch. Nothing in between, and one link to leave.

Sign in faster next time?

Add a passkey and skip the email link. Your fingerprint, face or device PIN is enough.