Effect.runSync

In the previous lesson we saw how to construct an Effect from a regular value. Today we’ll see how to extract a regular value from an Effect.

The previous lesson also highlighted that the Effect type does not expose any properties that we can access, apart from pipe. Rather than building rich objects with methods, the Effect ecosystem mostly revolves around building plain data objects and using functions to operate on those objects.

One such function is called Effect.runSync. Note that Effect is a namespace (not a class), and Effect.runSync is a function (not a static method).

Let’s construct an Effect and then run it.

import { Effect } from 'effect'
const program = Effect.succeed(3)
const result = Effect.runSync(program)
console.log(result)

Looking at the type signature, we can see that runSync takes an Effect<number> and returns a number.

const runSync: <number, never>(effect: Effect.Effect<number, never, never>) => number

Can you guess what the result will be when we run this code?

$ npx tsx main.ts
3

Sure enough, runSync will extract the value from the Effect.

Of course, running an Effect does not always produce a number. In general, it produces values of the same type as the “output” type of the Effect.

const runSync: <A, E>(effect: Effect.Effect<A, E, never>) => A

Conceptually - for now - you can think of an Effect as holding a value (of type A) that can be accessed later, when the Effect is run. We’ve called our variables program and result. These are typical names, and we shall see why in future lessons.

For example,

import { Effect } from 'effect'
const program = Effect.succeed("it can also produce a string")
const result = Effect.runSync(program)
console.log(result)

will print it can also produce a string.

From the name runSync, you may be able to guess that there are other ways of running an Effect. Indeed, there are quite a few: runPromise, runSyncExit, runFork, among others. We will see more of these as we progress.

Let’s recap.

  • Effect-the-module contains functions for constructing Effects and for running Effects.
  • Effect-the-data-type is a data type with up to 3 generic parameters.
  • The first parameter represents the type of the value that this Effect “holds”.
  • That value will be produced when the Effect runs.
  • You can run an Effect synchronously using Effect.runSync.