$ cat learning-effect-4-map-vs-flatmap.md
Part 4: map vs flatMap
$ tail -f learning-effect-4-map-vs-flatmap/readers
connecting…
I kept mixing up map and flatMap.
The rule is simple.
Use map when the callback returns a plain value.
Use flatMap when the callback returns an Effect.
That is it.
map changes the value
const program = Effect.succeed("ada").pipe( Effect.map((name) => name.toUpperCase()),);toUpperCase() returns a plain string.
So this is map.
flatMap continues the program
const program = parseUserId("1").pipe(Effect.flatMap((id) => fetchUser(id)));fetchUser(id) returns an Effect.
So this is flatMap.
The smell
If you use map with a function that returns an Effect, you get an Effect inside an Effect.
Effect.Effect<Effect.Effect<User, UserNotFound, never>, InvalidUserId, never>;That type is trying to tell you something.
You probably wanted flatMap.
What I am taking with me
The question is not “which operator do I like?”
The question is:
What does my callback return?
Plain value: map.
Effect value: flatMap.