Control Flow Operators
Even though JavaScript provides built-in control flow structures, Effect offers additional control flow functions that are useful in Effect applications. In this section, we will introduce different ways to control the flow of execution.
When working with Effect values, we can use standard JavaScript if-then-else statements:
Example (Returning None for Invalid Weight)
Here we are using the Option data type to represent the absence of a valid value.
1import { import Effect
Effect, import Option
Option } from "effect"2
3// Function to validate weight and return an Option4const const validateWeightOption: (weight: number) => Effect.Effect<Option.Option<number>>
validateWeightOption = (5 (parameter) weight: number
weight: number6): import Effect
Effect.interface Effect<out A, out E = never, out R = never>
namespace Effect
The `Effect` interface defines a value that lazily describes a workflow or job.
The workflow requires some context `R`, and may fail with an error of type `E`,
or succeed with a value of type `A`.
`Effect` values model resourceful interaction with the outside world, including
synchronous, asynchronous, concurrent, and parallel interaction. They use a
fiber-based concurrency model, with built-in support for scheduling, fine-grained
interruption, structured concurrency, and high scalability.
To run an `Effect` value, you need a `Runtime`, which is a type that is capable
of executing `Effect` values.
Effect<import Option
Option.type Option<A> = Option.None<A> | Option.Some<A>
namespace Option
Option<number>> => {7 if ((parameter) weight: number
weight >= 0) {8 // Return Some if the weight is valid9 return import Effect
Effect.const succeed: <Option.Option<number>>(value: Option.Option<number>) => Effect.Effect<Option.Option<number>, never, never>
Creates an `Effect` that succeeds with the provided value.
Use this function to represent a successful computation that yields a value of type `A`.
The effect does not fail and does not require any environmental context.
succeed(import Option
Option.const some: <number>(value: number) => Option.Option<number>
Creates a new `Option` that wraps the given value.
some((parameter) weight: number
weight))10 } else {11 // Return None if the weight is invalid12 return import Effect
Effect.const succeed: <Option.Option<number>>(value: Option.Option<number>) => Effect.Effect<Option.Option<number>, never, never>
Creates an `Effect` that succeeds with the provided value.
Use this function to represent a successful computation that yields a value of type `A`.
The effect does not fail and does not require any environmental context.
succeed(import Option
Option.const none: <number>() => Option.Option<number>
Creates a new `Option` that represents the absence of a value.
none())13 }14}
Example (Returning Error for Invalid Weight)
You can also handle invalid inputs by using the error channel, which allows you to return an error when the input is invalid:
1import { import Effect
Effect } from "effect"2
3// Function to validate weight or fail with an error4const const validateWeightOrFail: (weight: number) => Effect.Effect<number, string>
validateWeightOrFail = (5 (parameter) weight: number
weight: number6): import Effect
Effect.interface Effect<out A, out E = never, out R = never>
namespace Effect
The `Effect` interface defines a value that lazily describes a workflow or job.
The workflow requires some context `R`, and may fail with an error of type `E`,
or succeed with a value of type `A`.
`Effect` values model resourceful interaction with the outside world, including
synchronous, asynchronous, concurrent, and parallel interaction. They use a
fiber-based concurrency model, with built-in support for scheduling, fine-grained
interruption, structured concurrency, and high scalability.
To run an `Effect` value, you need a `Runtime`, which is a type that is capable
of executing `Effect` values.
Effect<number, string> => {7 if ((parameter) weight: number
weight >= 0) {8 // Return the weight if valid9 return import Effect
Effect.const succeed: <number>(value: number) => Effect.Effect<number, never, never>
Creates an `Effect` that succeeds with the provided value.
Use this function to represent a successful computation that yields a value of type `A`.
The effect does not fail and does not require any environmental context.
succeed((parameter) weight: number
weight)10 } else {11 // Fail with an error if invalid12 return import Effect
Effect.const fail: <string>(error: string) => Effect.Effect<never, string, never>
Creates an `Effect` that represents a recoverable error.
This `Effect` does not succeed but instead fails with the provided error. The
failure can be of any type, and will propagate through the effect pipeline
unless handled.
Use this function when you want to explicitly signal an error in an `Effect`
computation. The failed effect can later be handled with functions like
{@link
catchAll
}
or
{@link
catchTag
}
.
fail(`negative input: ${(parameter) weight: number
weight}`)13 }14}
Instead of using an if (condition) expression
, you can use the Effect.when
function to conditionally execute an effect based on a boolean condition.
Example (Conditional Effect Execution)
1import { import Effect
Effect, import Option
Option } from "effect"2
3const const validateWeightOption: (weight: number) => Effect.Effect<Option.Option<number>>
validateWeightOption = (4 (parameter) weight: number
weight: number5): import Effect
Effect.interface Effect<out A, out E = never, out R = never>
namespace Effect
The `Effect` interface defines a value that lazily describes a workflow or job.
The workflow requires some context `R`, and may fail with an error of type `E`,
or succeed with a value of type `A`.
`Effect` values model resourceful interaction with the outside world, including
synchronous, asynchronous, concurrent, and parallel interaction. They use a
fiber-based concurrency model, with built-in support for scheduling, fine-grained
interruption, structured concurrency, and high scalability.
To run an `Effect` value, you need a `Runtime`, which is a type that is capable
of executing `Effect` values.
Effect<import Option
Option.type Option<A> = Option.None<A> | Option.Some<A>
namespace Option
Option<number>> =>6 // Conditionally execute the effect if the weight is non-negative7 import Effect
Effect.const succeed: <number>(value: number) => Effect.Effect<number, never, never>
Creates an `Effect` that succeeds with the provided value.
Use this function to represent a successful computation that yields a value of type `A`.
The effect does not fail and does not require any environmental context.
succeed((parameter) weight: number
weight).(method) Pipeable.pipe<Effect.Effect<number, never, never>, Effect.Effect<Option.Option<number>, never, never>>(this: Effect.Effect<...>, ab: (_: Effect.Effect<number, never, never>) => Effect.Effect<...>): Effect.Effect<...> (+21 overloads)
pipe(import Effect
Effect.const when: (condition: LazyArg<boolean>) => <A, E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<Option.Option<A>, E, R> (+1 overload)
The moral equivalent of `if (p) exp`.
when(() => (parameter) weight: number
weight >= 0))8
9// Run with a valid weight10import Effect
Effect.const runPromise: <Option.Option<number>, never>(effect: Effect.Effect<Option.Option<number>, never, never>, options?: {
readonly signal?: AbortSignal;
} | undefined) => Promise<...>
Executes an effect and returns a `Promise` that resolves with the result.
Use `runPromise` when working with asynchronous effects and you need to integrate with code that uses Promises.
If the effect fails, the returned Promise will be rejected with the error.
runPromise(const validateWeightOption: (weight: number) => Effect.Effect<Option.Option<number>>
validateWeightOption(100)).(method) Promise<Option<number>>.then<void, never>(onfulfilled?: ((value: Option.Option<number>) => void | PromiseLike<void>) | null | undefined, onrejected?: ((reason: any) => PromiseLike<never>) | null | undefined): Promise<...>
Attaches callbacks for the resolution and/or rejection of the Promise.
then(namespace console
var console: Console
The `console` module provides a simple debugging console that is similar to the
JavaScript console mechanism provided by web browsers.
The module exports two specific components:
* A `Console` class with methods such as `console.log()`, `console.error()` and `console.warn()` that can be used to write to any Node.js stream.
* A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstdout) and
[`process.stderr`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstderr). The global `console` can be used without importing the `node:console` module.
_**Warning**_: The global console object's methods are neither consistently
synchronous like the browser APIs they resemble, nor are they consistently
asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v22.x/api/process.html#a-note-on-process-io) for
more information.
Example using the global `console`:
```js
console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoops, something bad happened
// at [eval]:5:15
// at Script.runInThisContext (node:vm:132:18)
// at Object.runInThisContext (node:vm:309:38)
// at node:internal/process/execution:77:19
// at [eval]-wrapper:6:22
// at evalScript (node:internal/process/execution:76:60)
// at node:internal/main/eval_string:23:3
const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr
```
Example using the `Console` class:
```js
const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);
myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err
```
console.(method) Console.log(message?: any, ...optionalParams: any[]): void
Prints to `stdout` with newline. Multiple arguments can be passed, with the
first used as the primary message and all additional used as substitution
values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html)
(the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args)).
```js
const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout
```
See [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args) for more information.
log)11/*12Output:13{14 _id: "Option",15 _tag: "Some",16 value: 10017}18*/19
20// Run with an invalid weight21import Effect
Effect.const runPromise: <Option.Option<number>, never>(effect: Effect.Effect<Option.Option<number>, never, never>, options?: {
readonly signal?: AbortSignal;
} | undefined) => Promise<...>
Executes an effect and returns a `Promise` that resolves with the result.
Use `runPromise` when working with asynchronous effects and you need to integrate with code that uses Promises.
If the effect fails, the returned Promise will be rejected with the error.
runPromise(const validateWeightOption: (weight: number) => Effect.Effect<Option.Option<number>>
validateWeightOption(-5)).(method) Promise<Option<number>>.then<void, never>(onfulfilled?: ((value: Option.Option<number>) => void | PromiseLike<void>) | null | undefined, onrejected?: ((reason: any) => PromiseLike<never>) | null | undefined): Promise<...>
Attaches callbacks for the resolution and/or rejection of the Promise.
then(namespace console
var console: Console
The `console` module provides a simple debugging console that is similar to the
JavaScript console mechanism provided by web browsers.
The module exports two specific components:
* A `Console` class with methods such as `console.log()`, `console.error()` and `console.warn()` that can be used to write to any Node.js stream.
* A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstdout) and
[`process.stderr`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstderr). The global `console` can be used without importing the `node:console` module.
_**Warning**_: The global console object's methods are neither consistently
synchronous like the browser APIs they resemble, nor are they consistently
asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v22.x/api/process.html#a-note-on-process-io) for
more information.
Example using the global `console`:
```js
console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoops, something bad happened
// at [eval]:5:15
// at Script.runInThisContext (node:vm:132:18)
// at Object.runInThisContext (node:vm:309:38)
// at node:internal/process/execution:77:19
// at [eval]-wrapper:6:22
// at evalScript (node:internal/process/execution:76:60)
// at node:internal/main/eval_string:23:3
const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr
```
Example using the `Console` class:
```js
const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);
myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err
```
console.(method) Console.log(message?: any, ...optionalParams: any[]): void
Prints to `stdout` with newline. Multiple arguments can be passed, with the
first used as the primary message and all additional used as substitution
values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html)
(the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args)).
```js
const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout
```
See [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args) for more information.
log)22/*23Output:24{25 _id: "Option",26 _tag: "None"27}28*/
In this example, the Option data type is used to represent the presence or absence of a valid value. If the condition evaluates to true
(in this case, if the weight is non-negative), the effect is executed and wrapped in a Some
. Otherwise, the result is None
.
If the condition itself involves an effect, you can use Effect.whenEffect
.
Example (Using an Effect as a Condition)
The following function creates a random integer, but only if a randomly generated boolean is true
.
1import { import Effect
Effect, import Random
Random } from "effect"2
3const const randomIntOption: Effect.Effect<Option<number>, never, never>
randomIntOption = import Random
Random.const nextInt: Effect.Effect<number, never, never>
Returns the next integer value from the pseudo-random number generator.
nextInt.(method) Pipeable.pipe<Effect.Effect<number, never, never>, Effect.Effect<Option<number>, never, never>>(this: Effect.Effect<...>, ab: (_: Effect.Effect<number, never, never>) => Effect.Effect<Option<number>, never, never>): Effect.Effect<...> (+21 overloads)
pipe(4 import Effect
Effect.const whenEffect: <never, never>(condition: Effect.Effect<boolean, never, never>) => <A, E2, R2>(effect: Effect.Effect<A, E2, R2>) => Effect.Effect<Option<A>, E2, R2> (+1 overload)
whenEffect(import Random
Random.const nextBoolean: Effect.Effect<boolean, never, never>
Returns the next boolean value from the pseudo-random number generator.
nextBoolean)5)6
7namespace console
var console: Console
The `console` module provides a simple debugging console that is similar to the
JavaScript console mechanism provided by web browsers.
The module exports two specific components:
* A `Console` class with methods such as `console.log()`, `console.error()` and `console.warn()` that can be used to write to any Node.js stream.
* A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstdout) and
[`process.stderr`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstderr). The global `console` can be used without importing the `node:console` module.
_**Warning**_: The global console object's methods are neither consistently
synchronous like the browser APIs they resemble, nor are they consistently
asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v22.x/api/process.html#a-note-on-process-io) for
more information.
Example using the global `console`:
```js
console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoops, something bad happened
// at [eval]:5:15
// at Script.runInThisContext (node:vm:132:18)
// at Object.runInThisContext (node:vm:309:38)
// at node:internal/process/execution:77:19
// at [eval]-wrapper:6:22
// at evalScript (node:internal/process/execution:76:60)
// at node:internal/main/eval_string:23:3
const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr
```
Example using the `Console` class:
```js
const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);
myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err
```
console.(method) Console.log(message?: any, ...optionalParams: any[]): void
Prints to `stdout` with newline. Multiple arguments can be passed, with the
first used as the primary message and all additional used as substitution
values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html)
(the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args)).
```js
const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout
```
See [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args) for more information.
log(import Effect
Effect.const runSync: <Option<number>, never>(effect: Effect.Effect<Option<number>, never, never>) => Option<number>
Executes an effect synchronously and returns its result.
Use `runSync` when you are certain that the effect is purely synchronous and will not perform any asynchronous operations.
If the effect fails or contains asynchronous tasks, it will throw an error.
runSync(const randomIntOption: Effect.Effect<Option<number>, never, never>
randomIntOption))8/*9Example Output:10{ _id: 'Option', _tag: 'Some', value: 8609104974198840 }11*/
The Effect.unless
and Effect.unlessEffect
functions are similar to the when*
functions, but they are equivalent to the if (!condition) expression
construct.
The Effect.if
function allows you to execute one of two effects based on an effectful predicate. If the predicate evaluates to true
, the onTrue
effect is run. If it evaluates to false
, the onFalse
effect is run instead.
Example (Simulating a Coin Flip)
In this example, we simulate a virtual coin flip using Random.nextBoolean
to generate a random boolean value. If the value is true
, the onTrue
effect logs “Head”. If the value is false
, the onFalse
effect logs “Tail”.
1import { import Effect
Effect, import Random
Random, import Console
Console } from "effect"2
3const const flipTheCoin: Effect.Effect<void, never, never>
flipTheCoin = import Effect
Effect.(alias) if<void, never, never, void, never, never, never, never>(self: boolean | Effect.Effect<boolean, never, never>, options: {
readonly onTrue: LazyArg<Effect.Effect<void, never, never>>;
readonly onFalse: LazyArg<...>;
}): Effect.Effect<...> (+1 overload)
export if
if(import Random
Random.const nextBoolean: Effect.Effect<boolean, never, never>
Returns the next boolean value from the pseudo-random number generator.
nextBoolean, {4 (property) onTrue: LazyArg<Effect.Effect<void, never, never>>
onTrue: () => import Console
Console.const log: (...args: ReadonlyArray<any>) => Effect.Effect<void>
log("Head"), // Runs if the predicate is true5 (property) onFalse: LazyArg<Effect.Effect<void, never, never>>
onFalse: () => import Console
Console.const log: (...args: ReadonlyArray<any>) => Effect.Effect<void>
log("Tail") // Runs if the predicate is false6})7
8import Effect
Effect.const runFork: <void, never>(effect: Effect.Effect<void, never, never>, options?: RunForkOptions) => RuntimeFiber<void, never>
Executes an effect and returns a `RuntimeFiber` that represents the running computation.
Use `runFork` when you want to start an effect without blocking the current execution flow.
It returns a fiber that you can observe, interrupt, or join as needed.
runFork(const flipTheCoin: Effect.Effect<void, never, never>
flipTheCoin)
The Effect.zip
function combines two effects into a single effect, producing a tuple with the results of both once they complete successfully.
Example (Combining Two Effects Sequentially)
1import { import Effect
Effect } from "effect"2
3const const task1: Effect.Effect<number, never, never>
task1 = import Effect
Effect.const succeed: <number>(value: number) => Effect.Effect<number, never, never>
Creates an `Effect` that succeeds with the provided value.
Use this function to represent a successful computation that yields a value of type `A`.
The effect does not fail and does not require any environmental context.
succeed(1).(method) Pipeable.pipe<Effect.Effect<number, never, never>, Effect.Effect<number, never, never>, Effect.Effect<number, never, never>>(this: Effect.Effect<...>, ab: (_: Effect.Effect<number, never, never>) => Effect.Effect<...>, bc: (_: Effect.Effect<...>) => Effect.Effect<...>): Effect.Effect<...> (+21 overloads)
pipe(4 import Effect
Effect.const delay: (duration: DurationInput) => <A, E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R> (+1 overload)
Returns an effect that is delayed from this effect by the specified
`Duration`.
delay("200 millis"),5 import Effect
Effect.const tap: <Effect.Effect<void, never, never>>(f: Effect.Effect<void, never, never>) => <A, E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R> (+7 overloads)
tap(import Effect
Effect.const log: (...message: ReadonlyArray<any>) => Effect.Effect<void, never, never>
Logs one or more messages or error causes at the current log level, which is INFO by default.
This function allows logging multiple items at once and can include detailed error information using `Cause` instances.
To adjust the log level, use the `Logger.withMinimumLogLevel` function.
log("task1 done"))6)7
8const const task2: Effect.Effect<string, never, never>
task2 = import Effect
Effect.const succeed: <string>(value: string) => Effect.Effect<string, never, never>
Creates an `Effect` that succeeds with the provided value.
Use this function to represent a successful computation that yields a value of type `A`.
The effect does not fail and does not require any environmental context.
succeed("hello").(method) Pipeable.pipe<Effect.Effect<string, never, never>, Effect.Effect<string, never, never>, Effect.Effect<string, never, never>>(this: Effect.Effect<...>, ab: (_: Effect.Effect<string, never, never>) => Effect.Effect<...>, bc: (_: Effect.Effect<...>) => Effect.Effect<...>): Effect.Effect<...> (+21 overloads)
pipe(9 import Effect
Effect.const delay: (duration: DurationInput) => <A, E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R> (+1 overload)
Returns an effect that is delayed from this effect by the specified
`Duration`.
delay("100 millis"),10 import Effect
Effect.const tap: <Effect.Effect<void, never, never>>(f: Effect.Effect<void, never, never>) => <A, E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R> (+7 overloads)
tap(import Effect
Effect.const log: (...message: ReadonlyArray<any>) => Effect.Effect<void, never, never>
Logs one or more messages or error causes at the current log level, which is INFO by default.
This function allows logging multiple items at once and can include detailed error information using `Cause` instances.
To adjust the log level, use the `Logger.withMinimumLogLevel` function.
log("task2 done"))11)12
13// Combine the two effects together14const const program: Effect.Effect<[number, string], never, never>
program = import Effect
Effect.const zip: <number, never, never, string, never, never>(self: Effect.Effect<number, never, never>, that: Effect.Effect<string, never, never>, options?: {
readonly concurrent?: boolean | undefined;
readonly batching?: boolean | "inherit" | undefined;
readonly concurrentFinalizers?: boolean | undefined;
} | undefined) => Effect.Effect<...> (+1 overload)
The `Effect.zip` function allows you to combine two effects into a single
effect. This combined effect yields a tuple containing the results of both
input effects once they succeed.
Note that `Effect.zip` processes effects sequentially: it first completes the
effect on the left and then the effect on the right.
If you want to run the effects concurrently, you can use the `concurrent` option.
zip(const task1: Effect.Effect<number, never, never>
task1, const task2: Effect.Effect<string, never, never>
task2)15
16import Effect
Effect.const runPromise: <[number, string], never>(effect: Effect.Effect<[number, string], never, never>, options?: {
readonly signal?: AbortSignal;
} | undefined) => Promise<[number, string]>
Executes an effect and returns a `Promise` that resolves with the result.
Use `runPromise` when working with asynchronous effects and you need to integrate with code that uses Promises.
If the effect fails, the returned Promise will be rejected with the error.
runPromise(const program: Effect.Effect<[number, string], never, never>
program).(method) Promise<[number, string]>.then<void, never>(onfulfilled?: ((value: [number, string]) => void | PromiseLike<void>) | null | undefined, onrejected?: ((reason: any) => PromiseLike<never>) | null | undefined): Promise<...>
Attaches callbacks for the resolution and/or rejection of the Promise.
then(namespace console
var console: Console
The `console` module provides a simple debugging console that is similar to the
JavaScript console mechanism provided by web browsers.
The module exports two specific components:
* A `Console` class with methods such as `console.log()`, `console.error()` and `console.warn()` that can be used to write to any Node.js stream.
* A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstdout) and
[`process.stderr`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstderr). The global `console` can be used without importing the `node:console` module.
_**Warning**_: The global console object's methods are neither consistently
synchronous like the browser APIs they resemble, nor are they consistently
asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v22.x/api/process.html#a-note-on-process-io) for
more information.
Example using the global `console`:
```js
console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoops, something bad happened
// at [eval]:5:15
// at Script.runInThisContext (node:vm:132:18)
// at Object.runInThisContext (node:vm:309:38)
// at node:internal/process/execution:77:19
// at [eval]-wrapper:6:22
// at evalScript (node:internal/process/execution:76:60)
// at node:internal/main/eval_string:23:3
const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr
```
Example using the `Console` class:
```js
const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);
myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err
```
console.(method) Console.log(message?: any, ...optionalParams: any[]): void
Prints to `stdout` with newline. Multiple arguments can be passed, with the
first used as the primary message and all additional used as substitution
values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html)
(the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args)).
```js
const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout
```
See [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args) for more information.
log)17/*18Output:19timestamp=... level=INFO fiber=#0 message="task1 done"20timestamp=... level=INFO fiber=#0 message="task2 done"21[ 1, 'hello' ]22*/
Note that Effect.zip
processes effects sequentially: it first completes the effect on the left and then the effect on the right.
If you want to run the effects concurrently, you can use the concurrent
option:
Example (Running Effects Concurrently)
1import { Effect } from "effect"2
9 collapsed lines
3const task1 = Effect.succeed(1).pipe(4 Effect.delay("200 millis"),5 Effect.tap(Effect.log("task1 done"))6)7
8const task2 = Effect.succeed("hello").pipe(9 Effect.delay("100 millis"),10 Effect.tap(Effect.log("task2 done"))11)12
13// Run both effects concurrently using the concurrent option14const program = Effect.zip(task1, task2, { concurrent: true })15
16Effect.runPromise(program).then(console.log)17/*18Output:19timestamp=... level=INFO fiber=#3 message="task2 done"20timestamp=... level=INFO fiber=#2 message="task1 done"21[ 1, 'hello' ]22*/
In this concurrent version, both effects run in parallel. task2
completes first, but both tasks can be logged and processed as soon as they’re done.
The Effect.zipWith
function, like Effect.zip
, combines two effects. However, instead of returning a tuple with the results, it lets you apply a function to the results of the effects, producing a single value.
Example (Combining Effects with a Custom Function)
1import { import Effect
Effect } from "effect"2
3const const task1: Effect.Effect<number, never, never>
task1 = import Effect
Effect.const succeed: <number>(value: number) => Effect.Effect<number, never, never>
Creates an `Effect` that succeeds with the provided value.
Use this function to represent a successful computation that yields a value of type `A`.
The effect does not fail and does not require any environmental context.
succeed(1).(method) Pipeable.pipe<Effect.Effect<number, never, never>, Effect.Effect<number, never, never>, Effect.Effect<number, never, never>>(this: Effect.Effect<...>, ab: (_: Effect.Effect<number, never, never>) => Effect.Effect<...>, bc: (_: Effect.Effect<...>) => Effect.Effect<...>): Effect.Effect<...> (+21 overloads)
pipe(4 import Effect
Effect.const delay: (duration: DurationInput) => <A, E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R> (+1 overload)
Returns an effect that is delayed from this effect by the specified
`Duration`.
delay("200 millis"),5 import Effect
Effect.const tap: <Effect.Effect<void, never, never>>(f: Effect.Effect<void, never, never>) => <A, E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R> (+7 overloads)
tap(import Effect
Effect.const log: (...message: ReadonlyArray<any>) => Effect.Effect<void, never, never>
Logs one or more messages or error causes at the current log level, which is INFO by default.
This function allows logging multiple items at once and can include detailed error information using `Cause` instances.
To adjust the log level, use the `Logger.withMinimumLogLevel` function.
log("task1 done"))6)7const const task2: Effect.Effect<string, never, never>
task2 = import Effect
Effect.const succeed: <string>(value: string) => Effect.Effect<string, never, never>
Creates an `Effect` that succeeds with the provided value.
Use this function to represent a successful computation that yields a value of type `A`.
The effect does not fail and does not require any environmental context.
succeed("hello").(method) Pipeable.pipe<Effect.Effect<string, never, never>, Effect.Effect<string, never, never>, Effect.Effect<string, never, never>>(this: Effect.Effect<...>, ab: (_: Effect.Effect<string, never, never>) => Effect.Effect<...>, bc: (_: Effect.Effect<...>) => Effect.Effect<...>): Effect.Effect<...> (+21 overloads)
pipe(8 import Effect
Effect.const delay: (duration: DurationInput) => <A, E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R> (+1 overload)
Returns an effect that is delayed from this effect by the specified
`Duration`.
delay("100 millis"),9 import Effect
Effect.const tap: <Effect.Effect<void, never, never>>(f: Effect.Effect<void, never, never>) => <A, E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R> (+7 overloads)
tap(import Effect
Effect.const log: (...message: ReadonlyArray<any>) => Effect.Effect<void, never, never>
Logs one or more messages or error causes at the current log level, which is INFO by default.
This function allows logging multiple items at once and can include detailed error information using `Cause` instances.
To adjust the log level, use the `Logger.withMinimumLogLevel` function.
log("task2 done"))10)11
12const const task3: Effect.Effect<number, never, never>
task3 = import Effect
Effect.const zipWith: <number, never, never, string, never, never, number>(self: Effect.Effect<number, never, never>, that: Effect.Effect<string, never, never>, f: (a: number, b: string) => number, options?: {
readonly concurrent?: boolean | undefined;
readonly batching?: boolean | "inherit" | undefined;
readonly concurrentFinalizers?: boolean | undefined;
}) => Effect.Effect<...> (+1 overload)
The `Effect.zipWith` function operates similarly to
{@link
zip
}
by combining
two effects. However, instead of returning a tuple, it allows you to apply a
function to the results of the combined effects, transforming them into a
single value
zipWith(13 const task1: Effect.Effect<number, never, never>
task1,14 const task2: Effect.Effect<string, never, never>
task2,15 // Combines results into a single value16 ((parameter) number: number
number, (parameter) string: string
string) => (parameter) number: number
number + (parameter) string: string
string.(property) String.length: number
Returns the length of a String object.
length17)18
19import Effect
Effect.const runPromise: <number, never>(effect: Effect.Effect<number, never, never>, options?: {
readonly signal?: AbortSignal;
} | undefined) => Promise<number>
Executes an effect and returns a `Promise` that resolves with the result.
Use `runPromise` when working with asynchronous effects and you need to integrate with code that uses Promises.
If the effect fails, the returned Promise will be rejected with the error.
runPromise(const task3: Effect.Effect<number, never, never>
task3).(method) Promise<number>.then<void, never>(onfulfilled?: ((value: number) => void | PromiseLike<void>) | null | undefined, onrejected?: ((reason: any) => PromiseLike<never>) | null | undefined): Promise<...>
Attaches callbacks for the resolution and/or rejection of the Promise.
then(namespace console
var console: Console
The `console` module provides a simple debugging console that is similar to the
JavaScript console mechanism provided by web browsers.
The module exports two specific components:
* A `Console` class with methods such as `console.log()`, `console.error()` and `console.warn()` that can be used to write to any Node.js stream.
* A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstdout) and
[`process.stderr`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstderr). The global `console` can be used without importing the `node:console` module.
_**Warning**_: The global console object's methods are neither consistently
synchronous like the browser APIs they resemble, nor are they consistently
asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v22.x/api/process.html#a-note-on-process-io) for
more information.
Example using the global `console`:
```js
console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoops, something bad happened
// at [eval]:5:15
// at Script.runInThisContext (node:vm:132:18)
// at Object.runInThisContext (node:vm:309:38)
// at node:internal/process/execution:77:19
// at [eval]-wrapper:6:22
// at evalScript (node:internal/process/execution:76:60)
// at node:internal/main/eval_string:23:3
const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr
```
Example using the `Console` class:
```js
const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);
myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err
```
console.(method) Console.log(message?: any, ...optionalParams: any[]): void
Prints to `stdout` with newline. Multiple arguments can be passed, with the
first used as the primary message and all additional used as substitution
values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html)
(the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args)).
```js
const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout
```
See [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args) for more information.
log)20/*21Output:22timestamp=... level=INFO fiber=#3 message="task1 done"23timestamp=... level=INFO fiber=#2 message="task2 done"24625*/
The Effect.loop
function allows you to repeatedly update a state using a step
function until a condition defined by the while
function becomes false
. It collects the intermediate states in an array and returns them as the final result.
Syntax
Effect.loop(initial, { while: (state) => boolean, step: (state) => state, body: (state) => Effect})
This function is similar to a while
loop in JavaScript, with the addition of effectful computations:
let state = initialconst result = []
while (options.while(state)) { result.push(options.body(state)) // Perform the effectful operation state = options.step(state) // Update the state}
return result
Example (Looping with Collected Results)
1import { import Effect
Effect } from "effect"2
3// A loop that runs 5 times, collecting each iteration's result4const const result: Effect.Effect<number[], never, never>
result = import Effect
Effect.const loop: <number, number, never, never>(initial: number, options: {
readonly while: (a: number) => boolean;
readonly step: (a: number) => number;
readonly body: (a: number) => Effect.Effect<number, never, never>;
readonly discard?: false | undefined;
}) => Effect.Effect<...> (+3 overloads)
The `Effect.loop` function allows you to repeatedly change the state based on an `step` function until a condition given by the `while` function is evaluated to `true`:
```ts
Effect.loop(initial, options: { while, step, body })
```
It collects all intermediate states in an array and returns it as the final result.
We can think of Effect.loop as equivalent to a while loop in JavaScript:
```ts
let state = initial
const result = []
while (options.while(state)) {
result.push(options.body(state))
state = options.step(state)
}
return result
```
loop(5 // Initial state6 1,7 {8 // Condition to continue looping9 (property) while: (a: number) => boolean
while: ((parameter) state: number
state) => (parameter) state: number
state <= 5,10 // State update function11 (property) step: (a: number) => number
step: ((parameter) state: number
state) => (parameter) state: number
state + 1,12 // Effect to be performed on each iteration13 (property) body: (a: number) => Effect.Effect<number, never, never>
body: ((parameter) state: number
state) => import Effect
Effect.const succeed: <number>(value: number) => Effect.Effect<number, never, never>
Creates an `Effect` that succeeds with the provided value.
Use this function to represent a successful computation that yields a value of type `A`.
The effect does not fail and does not require any environmental context.
succeed((parameter) state: number
state)14 }15)16
17import Effect
Effect.const runPromise: <number[], never>(effect: Effect.Effect<number[], never, never>, options?: {
readonly signal?: AbortSignal;
} | undefined) => Promise<number[]>
Executes an effect and returns a `Promise` that resolves with the result.
Use `runPromise` when working with asynchronous effects and you need to integrate with code that uses Promises.
If the effect fails, the returned Promise will be rejected with the error.
runPromise(const result: Effect.Effect<number[], never, never>
result).(method) Promise<number[]>.then<void, never>(onfulfilled?: ((value: number[]) => void | PromiseLike<void>) | null | undefined, onrejected?: ((reason: any) => PromiseLike<never>) | null | undefined): Promise<...>
Attaches callbacks for the resolution and/or rejection of the Promise.
then(namespace console
var console: Console
The `console` module provides a simple debugging console that is similar to the
JavaScript console mechanism provided by web browsers.
The module exports two specific components:
* A `Console` class with methods such as `console.log()`, `console.error()` and `console.warn()` that can be used to write to any Node.js stream.
* A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstdout) and
[`process.stderr`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstderr). The global `console` can be used without importing the `node:console` module.
_**Warning**_: The global console object's methods are neither consistently
synchronous like the browser APIs they resemble, nor are they consistently
asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v22.x/api/process.html#a-note-on-process-io) for
more information.
Example using the global `console`:
```js
console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoops, something bad happened
// at [eval]:5:15
// at Script.runInThisContext (node:vm:132:18)
// at Object.runInThisContext (node:vm:309:38)
// at node:internal/process/execution:77:19
// at [eval]-wrapper:6:22
// at evalScript (node:internal/process/execution:76:60)
// at node:internal/main/eval_string:23:3
const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr
```
Example using the `Console` class:
```js
const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);
myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err
```
console.(method) Console.log(message?: any, ...optionalParams: any[]): void
Prints to `stdout` with newline. Multiple arguments can be passed, with the
first used as the primary message and all additional used as substitution
values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html)
(the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args)).
```js
const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout
```
See [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args) for more information.
log)18// Output: [1, 2, 3, 4, 5]
In this example, the loop starts with the state 1
and continues until the state exceeds 5
. Each state is incremented by 1
and is collected into an array, which becomes the final result.
The discard
option, when set to true
, will discard the results of each effectful operation, returning void
instead of an array.
Example (Loop with Discarded Results)
1import { import Effect
Effect, import Console
Console } from "effect"2
3const const result: Effect.Effect<void, never, never>
result = import Effect
Effect.const loop: <number, void, never, never>(initial: number, options: {
readonly while: (a: number) => boolean;
readonly step: (a: number) => number;
readonly body: (a: number) => Effect.Effect<void, never, never>;
readonly discard: true;
}) => Effect.Effect<...> (+3 overloads)
The `Effect.loop` function allows you to repeatedly change the state based on an `step` function until a condition given by the `while` function is evaluated to `true`:
```ts
Effect.loop(initial, options: { while, step, body })
```
It collects all intermediate states in an array and returns it as the final result.
We can think of Effect.loop as equivalent to a while loop in JavaScript:
```ts
let state = initial
const result = []
while (options.while(state)) {
result.push(options.body(state))
state = options.step(state)
}
return result
```
loop(4 // Initial state5 1,6 {7 // Condition to continue looping8 (property) while: (a: number) => boolean
while: ((parameter) state: number
state) => (parameter) state: number
state <= 5,9 // State update function10 (property) step: (a: number) => number
step: ((parameter) state: number
state) => (parameter) state: number
state + 1,11 // Effect to be performed on each iteration12 (property) body: (a: number) => Effect.Effect<void, never, never>
body: ((parameter) state: number
state) => import Console
Console.const log: (...args: ReadonlyArray<any>) => Effect.Effect<void>
log(`Currently at state ${(parameter) state: number
state}`),13 // Discard intermediate results14 (property) discard: true
discard: true15 }16)17
18import Effect
Effect.const runPromise: <void, never>(effect: Effect.Effect<void, never, never>, options?: {
readonly signal?: AbortSignal;
} | undefined) => Promise<void>
Executes an effect and returns a `Promise` that resolves with the result.
Use `runPromise` when working with asynchronous effects and you need to integrate with code that uses Promises.
If the effect fails, the returned Promise will be rejected with the error.
runPromise(const result: Effect.Effect<void, never, never>
result).(method) Promise<void>.then<void, never>(onfulfilled?: ((value: void) => void | PromiseLike<void>) | null | undefined, onrejected?: ((reason: any) => PromiseLike<never>) | null | undefined): Promise<...>
Attaches callbacks for the resolution and/or rejection of the Promise.
then(namespace console
var console: Console
The `console` module provides a simple debugging console that is similar to the
JavaScript console mechanism provided by web browsers.
The module exports two specific components:
* A `Console` class with methods such as `console.log()`, `console.error()` and `console.warn()` that can be used to write to any Node.js stream.
* A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstdout) and
[`process.stderr`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstderr). The global `console` can be used without importing the `node:console` module.
_**Warning**_: The global console object's methods are neither consistently
synchronous like the browser APIs they resemble, nor are they consistently
asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v22.x/api/process.html#a-note-on-process-io) for
more information.
Example using the global `console`:
```js
console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoops, something bad happened
// at [eval]:5:15
// at Script.runInThisContext (node:vm:132:18)
// at Object.runInThisContext (node:vm:309:38)
// at node:internal/process/execution:77:19
// at [eval]-wrapper:6:22
// at evalScript (node:internal/process/execution:76:60)
// at node:internal/main/eval_string:23:3
const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr
```
Example using the `Console` class:
```js
const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);
myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err
```
console.(method) globalThis.Console.log(message?: any, ...optionalParams: any[]): void
Prints to `stdout` with newline. Multiple arguments can be passed, with the
first used as the primary message and all additional used as substitution
values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html)
(the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args)).
```js
const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout
```
See [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args) for more information.
log)19/*20Output:21Currently at state 122Currently at state 223Currently at state 324Currently at state 425Currently at state 526undefined27*/
In this example, the loop performs a side effect of logging the current index on each iteration, but it discards all intermediate results. The final result is undefined
.
The Effect.iterate
function lets you repeatedly update a state through an effectful operation. It runs the body
effect to update the state in each iteration and continues as long as the while
condition evaluates to true
.
Syntax
Effect.iterate(initial, { while: (result) => boolean, body: (result) => Effect})
This function is similar to a while
loop in JavaScript, with the addition of effectful computations:
let result = initial
while (options.while(result)) { result = options.body(result)}
return result
Example (Effectful Iteration)
1import { import Effect
Effect } from "effect"2
3const const result: Effect.Effect<number, never, never>
result = import Effect
Effect.const iterate: <number, never, never>(initial: number, options: {
readonly while: Predicate<number>;
readonly body: (a: number) => Effect.Effect<number, never, never>;
}) => Effect.Effect<number, never, never> (+1 overload)
The `Effect.iterate` function allows you to iterate with an effectful operation. It uses an effectful `body` operation to change the state during each iteration and continues the iteration as long as the `while` function evaluates to `true`:
```ts
Effect.iterate(initial, options: { while, body })
```
We can think of `Effect.iterate` as equivalent to a `while` loop in JavaScript:
```ts
let result = initial
while (options.while(result)) {
result = options.body(result)
}
return result
```
iterate(4 // Initial result5 1,6 {7 // Condition to continue iterating8 (property) while: Predicate<number>
while: ((parameter) result: number
result) => (parameter) result: number
result <= 5,9 // Operation to change the result10 (property) body: (a: number) => Effect.Effect<number, never, never>
body: ((parameter) result: number
result) => import Effect
Effect.const succeed: <number>(value: number) => Effect.Effect<number, never, never>
Creates an `Effect` that succeeds with the provided value.
Use this function to represent a successful computation that yields a value of type `A`.
The effect does not fail and does not require any environmental context.
succeed((parameter) result: number
result + 1)11 }12)13
14import Effect
Effect.const runPromise: <number, never>(effect: Effect.Effect<number, never, never>, options?: {
readonly signal?: AbortSignal;
} | undefined) => Promise<number>
Executes an effect and returns a `Promise` that resolves with the result.
Use `runPromise` when working with asynchronous effects and you need to integrate with code that uses Promises.
If the effect fails, the returned Promise will be rejected with the error.
runPromise(const result: Effect.Effect<number, never, never>
result).(method) Promise<number>.then<void, never>(onfulfilled?: ((value: number) => void | PromiseLike<void>) | null | undefined, onrejected?: ((reason: any) => PromiseLike<never>) | null | undefined): Promise<...>
Attaches callbacks for the resolution and/or rejection of the Promise.
then(namespace console
var console: Console
The `console` module provides a simple debugging console that is similar to the
JavaScript console mechanism provided by web browsers.
The module exports two specific components:
* A `Console` class with methods such as `console.log()`, `console.error()` and `console.warn()` that can be used to write to any Node.js stream.
* A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstdout) and
[`process.stderr`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstderr). The global `console` can be used without importing the `node:console` module.
_**Warning**_: The global console object's methods are neither consistently
synchronous like the browser APIs they resemble, nor are they consistently
asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v22.x/api/process.html#a-note-on-process-io) for
more information.
Example using the global `console`:
```js
console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoops, something bad happened
// at [eval]:5:15
// at Script.runInThisContext (node:vm:132:18)
// at Object.runInThisContext (node:vm:309:38)
// at node:internal/process/execution:77:19
// at [eval]-wrapper:6:22
// at evalScript (node:internal/process/execution:76:60)
// at node:internal/main/eval_string:23:3
const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr
```
Example using the `Console` class:
```js
const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);
myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err
```
console.(method) Console.log(message?: any, ...optionalParams: any[]): void
Prints to `stdout` with newline. Multiple arguments can be passed, with the
first used as the primary message and all additional used as substitution
values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html)
(the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args)).
```js
const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout
```
See [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args) for more information.
log)15// Output: 6
The Effect.forEach
function allows you to iterate over an Iterable
and perform an effectful operation for each element.
Syntax
const combinedEffect = Effect.forEach(iterable, operation, options)
It applies the specified effectful operation to each element in the Iterable
. By default, the effects are executed sequentially. If you’d like to explore options for controlling concurrency, refer to the Concurrency Options documentation.
This function returns a new effect that produces an array containing the results of each individual effect.
Example (Applying Effects to Iterable Elements)
1import { import Effect
Effect, import Console
Console } from "effect"2
3const const result: Effect.Effect<number[], never, never>
result = import Effect
Effect.const forEach: <number, never, never, number[]>(self: number[], f: (a: number, i: number) => Effect.Effect<number, never, never>, options?: {
readonly concurrency?: Concurrency | undefined;
readonly batching?: boolean | "inherit" | undefined;
readonly discard?: false | undefined;
readonly concurrentFinalizers?: boolean | undefined;
} | undefined) => Effect.Effect<...> (+3 overloads)
forEach([1, 2, 3, 4, 5], ((parameter) n: number
n, (parameter) index: number
index) =>4 import Console
Console.const log: (...args: ReadonlyArray<any>) => Effect.Effect<void>
log(`Currently at index ${(parameter) index: number
index}`).(method) Pipeable.pipe<Effect.Effect<void, never, never>, Effect.Effect<number, never, never>>(this: Effect.Effect<...>, ab: (_: Effect.Effect<void, never, never>) => Effect.Effect<number, never, never>): Effect.Effect<...> (+21 overloads)
pipe(import Effect
Effect.const as: <number>(value: number) => <A, E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<number, E, R> (+1 overload)
This function maps the success value of an `Effect` value to a specified
constant value.
as((parameter) n: number
n * 2))5)6
7import Effect
Effect.const runPromise: <number[], never>(effect: Effect.Effect<number[], never, never>, options?: {
readonly signal?: AbortSignal;
} | undefined) => Promise<number[]>
Executes an effect and returns a `Promise` that resolves with the result.
Use `runPromise` when working with asynchronous effects and you need to integrate with code that uses Promises.
If the effect fails, the returned Promise will be rejected with the error.
runPromise(const result: Effect.Effect<number[], never, never>
result).(method) Promise<number[]>.then<void, never>(onfulfilled?: ((value: number[]) => void | PromiseLike<void>) | null | undefined, onrejected?: ((reason: any) => PromiseLike<never>) | null | undefined): Promise<...>
Attaches callbacks for the resolution and/or rejection of the Promise.
then(namespace console
var console: Console
The `console` module provides a simple debugging console that is similar to the
JavaScript console mechanism provided by web browsers.
The module exports two specific components:
* A `Console` class with methods such as `console.log()`, `console.error()` and `console.warn()` that can be used to write to any Node.js stream.
* A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstdout) and
[`process.stderr`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstderr). The global `console` can be used without importing the `node:console` module.
_**Warning**_: The global console object's methods are neither consistently
synchronous like the browser APIs they resemble, nor are they consistently
asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v22.x/api/process.html#a-note-on-process-io) for
more information.
Example using the global `console`:
```js
console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoops, something bad happened
// at [eval]:5:15
// at Script.runInThisContext (node:vm:132:18)
// at Object.runInThisContext (node:vm:309:38)
// at node:internal/process/execution:77:19
// at [eval]-wrapper:6:22
// at evalScript (node:internal/process/execution:76:60)
// at node:internal/main/eval_string:23:3
const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr
```
Example using the `Console` class:
```js
const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);
myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err
```
console.(method) globalThis.Console.log(message?: any, ...optionalParams: any[]): void
Prints to `stdout` with newline. Multiple arguments can be passed, with the
first used as the primary message and all additional used as substitution
values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html)
(the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args)).
```js
const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout
```
See [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args) for more information.
log)8/*9Output:10Currently at index 011Currently at index 112Currently at index 213Currently at index 314Currently at index 415[ 2, 4, 6, 8, 10 ]16*/
In this example, we iterate over the array [1, 2, 3, 4, 5]
, applying an effect that logs the current index. The Effect.as(n * 2)
operation transforms each value, resulting in an array [2, 4, 6, 8, 10]
. The final output is the result of collecting all the transformed values.
The discard
option, when set to true
, will discard the results of each effectful operation, returning void
instead of an array.
Example (Using discard
to Ignore Results)
1import { import Effect
Effect, import Console
Console } from "effect"2
3// Apply effects but discard the results4const const result: Effect.Effect<void, never, never>
result = import Effect
Effect.const forEach: <number, number, never, never>(self: Iterable<number>, f: (a: number, i: number) => Effect.Effect<number, never, never>, options: {
readonly concurrency?: Concurrency | undefined;
readonly batching?: boolean | "inherit" | undefined;
readonly discard: true;
readonly concurrentFinalizers?: boolean | undefined;
}) => Effect.Effect<...> (+3 overloads)
forEach(5 [1, 2, 3, 4, 5],6 ((parameter) n: number
n, (parameter) index: number
index) =>7 import Console
Console.const log: (...args: ReadonlyArray<any>) => Effect.Effect<void>
log(`Currently at index ${(parameter) index: number
index}`).(method) Pipeable.pipe<Effect.Effect<void, never, never>, Effect.Effect<number, never, never>>(this: Effect.Effect<...>, ab: (_: Effect.Effect<void, never, never>) => Effect.Effect<number, never, never>): Effect.Effect<...> (+21 overloads)
pipe(import Effect
Effect.const as: <number>(value: number) => <A, E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<number, E, R> (+1 overload)
This function maps the success value of an `Effect` value to a specified
constant value.
as((parameter) n: number
n * 2)),8 { (property) discard: true
discard: true }9)10
11import Effect
Effect.const runPromise: <void, never>(effect: Effect.Effect<void, never, never>, options?: {
readonly signal?: AbortSignal;
} | undefined) => Promise<void>
Executes an effect and returns a `Promise` that resolves with the result.
Use `runPromise` when working with asynchronous effects and you need to integrate with code that uses Promises.
If the effect fails, the returned Promise will be rejected with the error.
runPromise(const result: Effect.Effect<void, never, never>
result).(method) Promise<void>.then<void, never>(onfulfilled?: ((value: void) => void | PromiseLike<void>) | null | undefined, onrejected?: ((reason: any) => PromiseLike<never>) | null | undefined): Promise<...>
Attaches callbacks for the resolution and/or rejection of the Promise.
then(namespace console
var console: Console
The `console` module provides a simple debugging console that is similar to the
JavaScript console mechanism provided by web browsers.
The module exports two specific components:
* A `Console` class with methods such as `console.log()`, `console.error()` and `console.warn()` that can be used to write to any Node.js stream.
* A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstdout) and
[`process.stderr`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstderr). The global `console` can be used without importing the `node:console` module.
_**Warning**_: The global console object's methods are neither consistently
synchronous like the browser APIs they resemble, nor are they consistently
asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v22.x/api/process.html#a-note-on-process-io) for
more information.
Example using the global `console`:
```js
console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoops, something bad happened
// at [eval]:5:15
// at Script.runInThisContext (node:vm:132:18)
// at Object.runInThisContext (node:vm:309:38)
// at node:internal/process/execution:77:19
// at [eval]-wrapper:6:22
// at evalScript (node:internal/process/execution:76:60)
// at node:internal/main/eval_string:23:3
const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr
```
Example using the `Console` class:
```js
const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);
myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err
```
console.(method) globalThis.Console.log(message?: any, ...optionalParams: any[]): void
Prints to `stdout` with newline. Multiple arguments can be passed, with the
first used as the primary message and all additional used as substitution
values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html)
(the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args)).
```js
const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout
```
See [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args) for more information.
log)12/*13Output:14Currently at index 015Currently at index 116Currently at index 217Currently at index 318Currently at index 419undefined20*/
In this case, the effects still run for each element, but the results are discarded, so the final output is undefined
.
The Effect.all
function is a versatile utility that allows you to combine multiple effects into one. It works with a variety of structures, such as tuples, iterables, structs, and records.
Syntax
const combinedEffect = Effect.all(effects, options)
Where effects
is a collection of effects to be combined.
By default, Effect.all
runs each effect sequentially. If you’d like to explore options for running effects concurrently or with other behaviors, refer to the Concurrency Options documentation.
The final result will match the structure of the input collection of effects.
Let’s explore examples for different types of structures: tuples, iterables, objects, and records.
Example (Combining Effects in Tuples)
1import { import Effect
Effect, import Console
Console } from "effect"2
3const const tuple: readonly [Effect.Effect<number, never, never>, Effect.Effect<string, never, never>]
tuple = [4 import Effect
Effect.const succeed: <number>(value: number) => Effect.Effect<number, never, never>
Creates an `Effect` that succeeds with the provided value.
Use this function to represent a successful computation that yields a value of type `A`.
The effect does not fail and does not require any environmental context.
succeed(42).(method) Pipeable.pipe<Effect.Effect<number, never, never>, Effect.Effect<number, never, never>>(this: Effect.Effect<...>, ab: (_: Effect.Effect<number, never, never>) => Effect.Effect<number, never, never>): Effect.Effect<...> (+21 overloads)
pipe(import Effect
Effect.const tap: <number, Effect.Effect<void, never, never>>(f: (a: number) => Effect.Effect<void, never, never>) => <E, R>(self: Effect.Effect<number, E, R>) => Effect.Effect<...> (+7 overloads)
tap(import Console
Console.const log: (...args: ReadonlyArray<any>) => Effect.Effect<void>
log)),5 import Effect
Effect.const succeed: <string>(value: string) => Effect.Effect<string, never, never>
Creates an `Effect` that succeeds with the provided value.
Use this function to represent a successful computation that yields a value of type `A`.
The effect does not fail and does not require any environmental context.
succeed("Hello").(method) Pipeable.pipe<Effect.Effect<string, never, never>, Effect.Effect<string, never, never>>(this: Effect.Effect<...>, ab: (_: Effect.Effect<string, never, never>) => Effect.Effect<string, never, never>): Effect.Effect<...> (+21 overloads)
pipe(import Effect
Effect.const tap: <string, Effect.Effect<void, never, never>>(f: (a: string) => Effect.Effect<void, never, never>) => <E, R>(self: Effect.Effect<string, E, R>) => Effect.Effect<...> (+7 overloads)
tap(import Console
Console.const log: (...args: ReadonlyArray<any>) => Effect.Effect<void>
log))6] as type const = readonly [Effect.Effect<number, never, never>, Effect.Effect<string, never, never>]
const7
8const const combinedEffect: Effect.Effect<[number, string], never, never>
combinedEffect = import Effect
Effect.const all: <readonly [Effect.Effect<number, never, never>, Effect.Effect<string, never, never>], {
readonly concurrency?: Concurrency | undefined;
readonly batching?: boolean | "inherit" | undefined;
readonly discard?: boolean | undefined;
readonly mode?: "default" | "validate" | "either" | undefined;
readonly concurrentFinalizers?: boolean | undefined;
}>(arg: readonly [...], options?: {
...;
} | undefined) => Effect.Effect<...>
Runs all the provided effects in sequence respecting the structure provided in input.
Supports multiple arguments, a single argument tuple / array or record / struct.
all(const tuple: readonly [Effect.Effect<number, never, never>, Effect.Effect<string, never, never>]
tuple)9
10import Effect
Effect.const runPromise: <[number, string], never>(effect: Effect.Effect<[number, string], never, never>, options?: {
readonly signal?: AbortSignal;
} | undefined) => Promise<[number, string]>
Executes an effect and returns a `Promise` that resolves with the result.
Use `runPromise` when working with asynchronous effects and you need to integrate with code that uses Promises.
If the effect fails, the returned Promise will be rejected with the error.
runPromise(const combinedEffect: Effect.Effect<[number, string], never, never>
combinedEffect).(method) Promise<[number, string]>.then<void, never>(onfulfilled?: ((value: [number, string]) => void | PromiseLike<void>) | null | undefined, onrejected?: ((reason: any) => PromiseLike<never>) | null | undefined): Promise<...>
Attaches callbacks for the resolution and/or rejection of the Promise.
then(namespace console
var console: Console
The `console` module provides a simple debugging console that is similar to the
JavaScript console mechanism provided by web browsers.
The module exports two specific components:
* A `Console` class with methods such as `console.log()`, `console.error()` and `console.warn()` that can be used to write to any Node.js stream.
* A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstdout) and
[`process.stderr`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstderr). The global `console` can be used without importing the `node:console` module.
_**Warning**_: The global console object's methods are neither consistently
synchronous like the browser APIs they resemble, nor are they consistently
asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v22.x/api/process.html#a-note-on-process-io) for
more information.
Example using the global `console`:
```js
console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoops, something bad happened
// at [eval]:5:15
// at Script.runInThisContext (node:vm:132:18)
// at Object.runInThisContext (node:vm:309:38)
// at node:internal/process/execution:77:19
// at [eval]-wrapper:6:22
// at evalScript (node:internal/process/execution:76:60)
// at node:internal/main/eval_string:23:3
const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr
```
Example using the `Console` class:
```js
const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);
myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err
```
console.(method) globalThis.Console.log(message?: any, ...optionalParams: any[]): void
Prints to `stdout` with newline. Multiple arguments can be passed, with the
first used as the primary message and all additional used as substitution
values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html)
(the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args)).
```js
const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout
```
See [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args) for more information.
log)11/*12Output:134214Hello15[ 42, 'Hello' ]16*/
Example (Combining Effects in Iterables)
1import { import Effect
Effect, import Console
Console } from "effect"2
3const const iterable: Iterable<Effect.Effect<number, never, never>>
iterable: interface Iterable<T, TReturn = any, TNext = any>
Iterable<import Effect
Effect.interface Effect<out A, out E = never, out R = never>
namespace Effect
The `Effect` interface defines a value that lazily describes a workflow or job.
The workflow requires some context `R`, and may fail with an error of type `E`,
or succeed with a value of type `A`.
`Effect` values model resourceful interaction with the outside world, including
synchronous, asynchronous, concurrent, and parallel interaction. They use a
fiber-based concurrency model, with built-in support for scheduling, fine-grained
interruption, structured concurrency, and high scalability.
To run an `Effect` value, you need a `Runtime`, which is a type that is capable
of executing `Effect` values.
Effect<number>> = [1, 2, 3].(method) Array<number>.map<Effect.Effect<number, never, never>>(callbackfn: (value: number, index: number, array: number[]) => Effect.Effect<number, never, never>, thisArg?: any): Effect.Effect<...>[]
Calls a defined callback function on each element of an array, and returns an array that contains the results.
map(((parameter) n: number
n) =>4 import Effect
Effect.const succeed: <number>(value: number) => Effect.Effect<number, never, never>
Creates an `Effect` that succeeds with the provided value.
Use this function to represent a successful computation that yields a value of type `A`.
The effect does not fail and does not require any environmental context.
succeed((parameter) n: number
n).(method) Pipeable.pipe<Effect.Effect<number, never, never>, Effect.Effect<number, never, never>>(this: Effect.Effect<...>, ab: (_: Effect.Effect<number, never, never>) => Effect.Effect<number, never, never>): Effect.Effect<...> (+21 overloads)
pipe(import Effect
Effect.const tap: <number, Effect.Effect<void, never, never>>(f: (a: number) => Effect.Effect<void, never, never>) => <E, R>(self: Effect.Effect<number, E, R>) => Effect.Effect<...> (+7 overloads)
tap(import Console
Console.const log: (...args: ReadonlyArray<any>) => Effect.Effect<void>
log))5)6
7const const combinedEffect: Effect.Effect<number[], never, never>
combinedEffect = import Effect
Effect.const all: <Iterable<Effect.Effect<number, never, never>>, {
readonly concurrency?: Concurrency | undefined;
readonly batching?: boolean | "inherit" | undefined;
readonly discard?: boolean | undefined;
readonly mode?: "default" | "validate" | "either" | undefined;
readonly concurrentFinalizers?: boolean | undefined;
}>(arg: Iterable<...>, options?: {
...;
} | undefined) => Effect.Effect<...>
Runs all the provided effects in sequence respecting the structure provided in input.
Supports multiple arguments, a single argument tuple / array or record / struct.
all(const iterable: Iterable<Effect.Effect<number, never, never>>
iterable)8
9import Effect
Effect.const runPromise: <number[], never>(effect: Effect.Effect<number[], never, never>, options?: {
readonly signal?: AbortSignal;
} | undefined) => Promise<number[]>
Executes an effect and returns a `Promise` that resolves with the result.
Use `runPromise` when working with asynchronous effects and you need to integrate with code that uses Promises.
If the effect fails, the returned Promise will be rejected with the error.
runPromise(const combinedEffect: Effect.Effect<number[], never, never>
combinedEffect).(method) Promise<number[]>.then<void, never>(onfulfilled?: ((value: number[]) => void | PromiseLike<void>) | null | undefined, onrejected?: ((reason: any) => PromiseLike<never>) | null | undefined): Promise<...>
Attaches callbacks for the resolution and/or rejection of the Promise.
then(namespace console
var console: Console
The `console` module provides a simple debugging console that is similar to the
JavaScript console mechanism provided by web browsers.
The module exports two specific components:
* A `Console` class with methods such as `console.log()`, `console.error()` and `console.warn()` that can be used to write to any Node.js stream.
* A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstdout) and
[`process.stderr`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstderr). The global `console` can be used without importing the `node:console` module.
_**Warning**_: The global console object's methods are neither consistently
synchronous like the browser APIs they resemble, nor are they consistently
asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v22.x/api/process.html#a-note-on-process-io) for
more information.
Example using the global `console`:
```js
console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoops, something bad happened
// at [eval]:5:15
// at Script.runInThisContext (node:vm:132:18)
// at Object.runInThisContext (node:vm:309:38)
// at node:internal/process/execution:77:19
// at [eval]-wrapper:6:22
// at evalScript (node:internal/process/execution:76:60)
// at node:internal/main/eval_string:23:3
const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr
```
Example using the `Console` class:
```js
const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);
myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err
```
console.(method) globalThis.Console.log(message?: any, ...optionalParams: any[]): void
Prints to `stdout` with newline. Multiple arguments can be passed, with the
first used as the primary message and all additional used as substitution
values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html)
(the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args)).
```js
const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout
```
See [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args) for more information.
log)10/*11Output:12113214315[ 1, 2, 3 ]16*/
Example (Combining Effects in Structs)
1import { import Effect
Effect, import Console
Console } from "effect"2
3const const struct: {
a: Effect.Effect<number, never, never>;
b: Effect.Effect<string, never, never>;
}
struct = {4 (property) a: Effect.Effect<number, never, never>
a: import Effect
Effect.const succeed: <number>(value: number) => Effect.Effect<number, never, never>
Creates an `Effect` that succeeds with the provided value.
Use this function to represent a successful computation that yields a value of type `A`.
The effect does not fail and does not require any environmental context.
succeed(42).(method) Pipeable.pipe<Effect.Effect<number, never, never>, Effect.Effect<number, never, never>>(this: Effect.Effect<...>, ab: (_: Effect.Effect<number, never, never>) => Effect.Effect<number, never, never>): Effect.Effect<...> (+21 overloads)
pipe(import Effect
Effect.const tap: <number, Effect.Effect<void, never, never>>(f: (a: number) => Effect.Effect<void, never, never>) => <E, R>(self: Effect.Effect<number, E, R>) => Effect.Effect<...> (+7 overloads)
tap(import Console
Console.const log: (...args: ReadonlyArray<any>) => Effect.Effect<void>
log)),5 (property) b: Effect.Effect<string, never, never>
b: import Effect
Effect.const succeed: <string>(value: string) => Effect.Effect<string, never, never>
Creates an `Effect` that succeeds with the provided value.
Use this function to represent a successful computation that yields a value of type `A`.
The effect does not fail and does not require any environmental context.
succeed("Hello").(method) Pipeable.pipe<Effect.Effect<string, never, never>, Effect.Effect<string, never, never>>(this: Effect.Effect<...>, ab: (_: Effect.Effect<string, never, never>) => Effect.Effect<string, never, never>): Effect.Effect<...> (+21 overloads)
pipe(import Effect
Effect.const tap: <string, Effect.Effect<void, never, never>>(f: (a: string) => Effect.Effect<void, never, never>) => <E, R>(self: Effect.Effect<string, E, R>) => Effect.Effect<...> (+7 overloads)
tap(import Console
Console.const log: (...args: ReadonlyArray<any>) => Effect.Effect<void>
log))6}7
8const const combinedEffect: Effect.Effect<{
a: number;
b: string;
}, never, never>
combinedEffect = import Effect
Effect.const all: <{
a: Effect.Effect<number, never, never>;
b: Effect.Effect<string, never, never>;
}, {
readonly concurrency?: Concurrency | undefined;
readonly batching?: boolean | "inherit" | undefined;
readonly discard?: boolean | undefined;
readonly mode?: "default" | "validate" | "either" | undefined;
readonly concurrentFinalizers?: boolean | undefined;
}>(arg: {
...;
}, options?: {
...;
} | undefined) => Effect.Effect<...>
Runs all the provided effects in sequence respecting the structure provided in input.
Supports multiple arguments, a single argument tuple / array or record / struct.
all(const struct: {
a: Effect.Effect<number, never, never>;
b: Effect.Effect<string, never, never>;
}
struct)9
10import Effect
Effect.const runPromise: <{
a: number;
b: string;
}, never>(effect: Effect.Effect<{
a: number;
b: string;
}, never, never>, options?: {
readonly signal?: AbortSignal;
} | undefined) => Promise<{
a: number;
b: string;
}>
Executes an effect and returns a `Promise` that resolves with the result.
Use `runPromise` when working with asynchronous effects and you need to integrate with code that uses Promises.
If the effect fails, the returned Promise will be rejected with the error.
runPromise(const combinedEffect: Effect.Effect<{
a: number;
b: string;
}, never, never>
combinedEffect).(method) Promise<{ a: number; b: string; }>.then<void, never>(onfulfilled?: ((value: {
a: number;
b: string;
}) => void | PromiseLike<void>) | null | undefined, onrejected?: ((reason: any) => PromiseLike<never>) | null | undefined): Promise<...>
Attaches callbacks for the resolution and/or rejection of the Promise.
then(namespace console
var console: Console
The `console` module provides a simple debugging console that is similar to the
JavaScript console mechanism provided by web browsers.
The module exports two specific components:
* A `Console` class with methods such as `console.log()`, `console.error()` and `console.warn()` that can be used to write to any Node.js stream.
* A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstdout) and
[`process.stderr`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstderr). The global `console` can be used without importing the `node:console` module.
_**Warning**_: The global console object's methods are neither consistently
synchronous like the browser APIs they resemble, nor are they consistently
asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v22.x/api/process.html#a-note-on-process-io) for
more information.
Example using the global `console`:
```js
console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoops, something bad happened
// at [eval]:5:15
// at Script.runInThisContext (node:vm:132:18)
// at Object.runInThisContext (node:vm:309:38)
// at node:internal/process/execution:77:19
// at [eval]-wrapper:6:22
// at evalScript (node:internal/process/execution:76:60)
// at node:internal/main/eval_string:23:3
const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr
```
Example using the `Console` class:
```js
const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);
myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err
```
console.(method) globalThis.Console.log(message?: any, ...optionalParams: any[]): void
Prints to `stdout` with newline. Multiple arguments can be passed, with the
first used as the primary message and all additional used as substitution
values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html)
(the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args)).
```js
const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout
```
See [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args) for more information.
log)11/*12Output:134214Hello15{ a: 42, b: 'Hello' }16*/
Example (Combining Effects in Records)
1import { import Effect
Effect, import Console
Console } from "effect"2
3const const record: Record<string, Effect.Effect<number, never, never>>
record: type Record<K extends keyof any, T> = { [P in K]: T; }
Construct a type with a set of properties K of type T
Record<string, import Effect
Effect.interface Effect<out A, out E = never, out R = never>
namespace Effect
The `Effect` interface defines a value that lazily describes a workflow or job.
The workflow requires some context `R`, and may fail with an error of type `E`,
or succeed with a value of type `A`.
`Effect` values model resourceful interaction with the outside world, including
synchronous, asynchronous, concurrent, and parallel interaction. They use a
fiber-based concurrency model, with built-in support for scheduling, fine-grained
interruption, structured concurrency, and high scalability.
To run an `Effect` value, you need a `Runtime`, which is a type that is capable
of executing `Effect` values.
Effect<number>> = {4 (property) key1: Effect.Effect<number, never, never>
key1: import Effect
Effect.const succeed: <number>(value: number) => Effect.Effect<number, never, never>
Creates an `Effect` that succeeds with the provided value.
Use this function to represent a successful computation that yields a value of type `A`.
The effect does not fail and does not require any environmental context.
succeed(1).(method) Pipeable.pipe<Effect.Effect<number, never, never>, Effect.Effect<number, never, never>>(this: Effect.Effect<...>, ab: (_: Effect.Effect<number, never, never>) => Effect.Effect<number, never, never>): Effect.Effect<...> (+21 overloads)
pipe(import Effect
Effect.const tap: <number, Effect.Effect<void, never, never>>(f: (a: number) => Effect.Effect<void, never, never>) => <E, R>(self: Effect.Effect<number, E, R>) => Effect.Effect<...> (+7 overloads)
tap(import Console
Console.const log: (...args: ReadonlyArray<any>) => Effect.Effect<void>
log)),5 (property) key2: Effect.Effect<number, never, never>
key2: import Effect
Effect.const succeed: <number>(value: number) => Effect.Effect<number, never, never>
Creates an `Effect` that succeeds with the provided value.
Use this function to represent a successful computation that yields a value of type `A`.
The effect does not fail and does not require any environmental context.
succeed(2).(method) Pipeable.pipe<Effect.Effect<number, never, never>, Effect.Effect<number, never, never>>(this: Effect.Effect<...>, ab: (_: Effect.Effect<number, never, never>) => Effect.Effect<number, never, never>): Effect.Effect<...> (+21 overloads)
pipe(import Effect
Effect.const tap: <number, Effect.Effect<void, never, never>>(f: (a: number) => Effect.Effect<void, never, never>) => <E, R>(self: Effect.Effect<number, E, R>) => Effect.Effect<...> (+7 overloads)
tap(import Console
Console.const log: (...args: ReadonlyArray<any>) => Effect.Effect<void>
log))6}7
8const const combinedEffect: Effect.Effect<{
[x: string]: number;
}, never, never>
combinedEffect = import Effect
Effect.const all: <Record<string, Effect.Effect<number, never, never>>, {
readonly concurrency?: Concurrency | undefined;
readonly batching?: boolean | "inherit" | undefined;
readonly discard?: boolean | undefined;
readonly mode?: "default" | "validate" | "either" | undefined;
readonly concurrentFinalizers?: boolean | undefined;
}>(arg: Record<...>, options?: {
...;
} | undefined) => Effect.Effect<...>
Runs all the provided effects in sequence respecting the structure provided in input.
Supports multiple arguments, a single argument tuple / array or record / struct.
all(const record: Record<string, Effect.Effect<number, never, never>>
record)9
10import Effect
Effect.const runPromise: <{
[x: string]: number;
}, never>(effect: Effect.Effect<{
[x: string]: number;
}, never, never>, options?: {
readonly signal?: AbortSignal;
} | undefined) => Promise<{
[x: string]: number;
}>
Executes an effect and returns a `Promise` that resolves with the result.
Use `runPromise` when working with asynchronous effects and you need to integrate with code that uses Promises.
If the effect fails, the returned Promise will be rejected with the error.
runPromise(const combinedEffect: Effect.Effect<{
[x: string]: number;
}, never, never>
combinedEffect).(method) Promise<{ [x: string]: number; }>.then<void, never>(onfulfilled?: ((value: {
[x: string]: number;
}) => void | PromiseLike<void>) | null | undefined, onrejected?: ((reason: any) => PromiseLike<never>) | null | undefined): Promise<...>
Attaches callbacks for the resolution and/or rejection of the Promise.
then(namespace console
var console: Console
The `console` module provides a simple debugging console that is similar to the
JavaScript console mechanism provided by web browsers.
The module exports two specific components:
* A `Console` class with methods such as `console.log()`, `console.error()` and `console.warn()` that can be used to write to any Node.js stream.
* A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstdout) and
[`process.stderr`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstderr). The global `console` can be used without importing the `node:console` module.
_**Warning**_: The global console object's methods are neither consistently
synchronous like the browser APIs they resemble, nor are they consistently
asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v22.x/api/process.html#a-note-on-process-io) for
more information.
Example using the global `console`:
```js
console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoops, something bad happened
// at [eval]:5:15
// at Script.runInThisContext (node:vm:132:18)
// at Object.runInThisContext (node:vm:309:38)
// at node:internal/process/execution:77:19
// at [eval]-wrapper:6:22
// at evalScript (node:internal/process/execution:76:60)
// at node:internal/main/eval_string:23:3
const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr
```
Example using the `Console` class:
```js
const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);
myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err
```
console.(method) globalThis.Console.log(message?: any, ...optionalParams: any[]): void
Prints to `stdout` with newline. Multiple arguments can be passed, with the
first used as the primary message and all additional used as substitution
values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html)
(the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args)).
```js
const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout
```
See [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args) for more information.
log)11/*12Output:13114215{ key1: 1, key2: 2 }16*/
The Effect.all
function stops execution on the first error it encounters, this is called short-circuiting.
If any effect in the collection fails, the remaining effects will not run, and the error will be propagated.
1import { import Effect
Effect, import Console
Console } from "effect"2
3const const effects: (Effect.Effect<string, never, never> | Effect.Effect<never, string, never>)[]
effects = [4 import Effect
Effect.const succeed: <string>(value: string) => Effect.Effect<string, never, never>
Creates an `Effect` that succeeds with the provided value.
Use this function to represent a successful computation that yields a value of type `A`.
The effect does not fail and does not require any environmental context.
succeed("Task1").(method) Pipeable.pipe<Effect.Effect<string, never, never>, Effect.Effect<string, never, never>>(this: Effect.Effect<...>, ab: (_: Effect.Effect<string, never, never>) => Effect.Effect<string, never, never>): Effect.Effect<...> (+21 overloads)
pipe(import Effect
Effect.const tap: <string, Effect.Effect<void, never, never>>(f: (a: string) => Effect.Effect<void, never, never>) => <E, R>(self: Effect.Effect<string, E, R>) => Effect.Effect<...> (+7 overloads)
tap(import Console
Console.const log: (...args: ReadonlyArray<any>) => Effect.Effect<void>
log)),5 import Effect
Effect.const fail: <string>(error: string) => Effect.Effect<never, string, never>
Creates an `Effect` that represents a recoverable error.
This `Effect` does not succeed but instead fails with the provided error. The
failure can be of any type, and will propagate through the effect pipeline
unless handled.
Use this function when you want to explicitly signal an error in an `Effect`
computation. The failed effect can later be handled with functions like
{@link
catchAll
}
or
{@link
catchTag
}
.
fail("Task2: Oh no!").(method) Pipeable.pipe<Effect.Effect<never, string, never>, Effect.Effect<never, string, never>>(this: Effect.Effect<...>, ab: (_: Effect.Effect<never, string, never>) => Effect.Effect<never, string, never>): Effect.Effect<...> (+21 overloads)
pipe(import Effect
Effect.const tap: <never, Effect.Effect<void, never, never>>(f: (a: never) => Effect.Effect<void, never, never>) => <E, R>(self: Effect.Effect<never, E, R>) => Effect.Effect<...> (+7 overloads)
tap(import Console
Console.const log: (...args: ReadonlyArray<any>) => Effect.Effect<void>
log)),6 // Won't execute due to earlier failure7 import Effect
Effect.const succeed: <string>(value: string) => Effect.Effect<string, never, never>
Creates an `Effect` that succeeds with the provided value.
Use this function to represent a successful computation that yields a value of type `A`.
The effect does not fail and does not require any environmental context.
succeed("Task3").(method) Pipeable.pipe<Effect.Effect<string, never, never>, Effect.Effect<string, never, never>>(this: Effect.Effect<...>, ab: (_: Effect.Effect<string, never, never>) => Effect.Effect<string, never, never>): Effect.Effect<...> (+21 overloads)
pipe(import Effect
Effect.const tap: <string, Effect.Effect<void, never, never>>(f: (a: string) => Effect.Effect<void, never, never>) => <E, R>(self: Effect.Effect<string, E, R>) => Effect.Effect<...> (+7 overloads)
tap(import Console
Console.const log: (...args: ReadonlyArray<any>) => Effect.Effect<void>
log))8]9
10const const program: Effect.Effect<string[], string, never>
program = import Effect
Effect.const all: <(Effect.Effect<string, never, never> | Effect.Effect<never, string, never>)[], {
readonly concurrency?: Concurrency | undefined;
readonly batching?: boolean | "inherit" | undefined;
readonly discard?: boolean | undefined;
readonly mode?: "default" | "validate" | "either" | undefined;
readonly concurrentFinalizers?: boolean | undefined;
}>(arg: (Effect.Effect<...> | Effect.Effect<...>)[], options?: {
...;
} | undefined) => Effect.Effect<...>
Runs all the provided effects in sequence respecting the structure provided in input.
Supports multiple arguments, a single argument tuple / array or record / struct.
all(const effects: (Effect.Effect<string, never, never> | Effect.Effect<never, string, never>)[]
effects)11
12import Effect
Effect.const runPromiseExit: <string[], string>(effect: Effect.Effect<string[], string, never>, options?: {
readonly signal?: AbortSignal;
} | undefined) => Promise<Exit<string[], string>>
Executes an effect and returns a `Promise` that resolves with an `Exit` describing the result.
Use `runPromiseExit` when you need detailed information about the outcome of the effect, including success or failure,
and you want to work with Promises.
runPromiseExit(const program: Effect.Effect<string[], string, never>
program).(method) Promise<Exit<string[], string>>.then<void, never>(onfulfilled?: ((value: Exit<string[], string>) => void | PromiseLike<void>) | null | undefined, onrejected?: ((reason: any) => PromiseLike<never>) | null | undefined): Promise<...>
Attaches callbacks for the resolution and/or rejection of the Promise.
then(namespace console
var console: Console
The `console` module provides a simple debugging console that is similar to the
JavaScript console mechanism provided by web browsers.
The module exports two specific components:
* A `Console` class with methods such as `console.log()`, `console.error()` and `console.warn()` that can be used to write to any Node.js stream.
* A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstdout) and
[`process.stderr`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstderr). The global `console` can be used without importing the `node:console` module.
_**Warning**_: The global console object's methods are neither consistently
synchronous like the browser APIs they resemble, nor are they consistently
asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v22.x/api/process.html#a-note-on-process-io) for
more information.
Example using the global `console`:
```js
console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoops, something bad happened
// at [eval]:5:15
// at Script.runInThisContext (node:vm:132:18)
// at Object.runInThisContext (node:vm:309:38)
// at node:internal/process/execution:77:19
// at [eval]-wrapper:6:22
// at evalScript (node:internal/process/execution:76:60)
// at node:internal/main/eval_string:23:3
const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr
```
Example using the `Console` class:
```js
const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);
myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err
```
console.(method) globalThis.Console.log(message?: any, ...optionalParams: any[]): void
Prints to `stdout` with newline. Multiple arguments can be passed, with the
first used as the primary message and all additional used as substitution
values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html)
(the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args)).
```js
const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout
```
See [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args) for more information.
log)13/*14Output:15Task116{17 _id: 'Exit',18 _tag: 'Failure',19 cause: { _id: 'Cause', _tag: 'Fail', failure: 'Task2: Oh no!' }20}21*/
You can override this behavior by using the mode
option.
The { mode: "either" }
option changes the behavior of Effect.all
to ensure all effects run, even if some fail. Instead of stopping on the first failure, this mode collects both successes and failures, returning an array of Either
instances where each result is either a Right
(success) or a Left
(failure).
Example (mode: "either"
)
1import { import Effect
Effect, import Console
Console } from "effect"2
3const const effects: (Effect.Effect<string, never, never> | Effect.Effect<never, string, never>)[]
effects = [4 import Effect
Effect.const succeed: <string>(value: string) => Effect.Effect<string, never, never>
Creates an `Effect` that succeeds with the provided value.
Use this function to represent a successful computation that yields a value of type `A`.
The effect does not fail and does not require any environmental context.
succeed("Task1").(method) Pipeable.pipe<Effect.Effect<string, never, never>, Effect.Effect<string, never, never>>(this: Effect.Effect<...>, ab: (_: Effect.Effect<string, never, never>) => Effect.Effect<string, never, never>): Effect.Effect<...> (+21 overloads)
pipe(import Effect
Effect.const tap: <string, Effect.Effect<void, never, never>>(f: (a: string) => Effect.Effect<void, never, never>) => <E, R>(self: Effect.Effect<string, E, R>) => Effect.Effect<...> (+7 overloads)
tap(import Console
Console.const log: (...args: ReadonlyArray<any>) => Effect.Effect<void>
log)),5 import Effect
Effect.const fail: <string>(error: string) => Effect.Effect<never, string, never>
Creates an `Effect` that represents a recoverable error.
This `Effect` does not succeed but instead fails with the provided error. The
failure can be of any type, and will propagate through the effect pipeline
unless handled.
Use this function when you want to explicitly signal an error in an `Effect`
computation. The failed effect can later be handled with functions like
{@link
catchAll
}
or
{@link
catchTag
}
.
fail("Task2: Oh no!").(method) Pipeable.pipe<Effect.Effect<never, string, never>, Effect.Effect<never, string, never>>(this: Effect.Effect<...>, ab: (_: Effect.Effect<never, string, never>) => Effect.Effect<never, string, never>): Effect.Effect<...> (+21 overloads)
pipe(import Effect
Effect.const tap: <never, Effect.Effect<void, never, never>>(f: (a: never) => Effect.Effect<void, never, never>) => <E, R>(self: Effect.Effect<never, E, R>) => Effect.Effect<...> (+7 overloads)
tap(import Console
Console.const log: (...args: ReadonlyArray<any>) => Effect.Effect<void>
log)),6 import Effect
Effect.const succeed: <string>(value: string) => Effect.Effect<string, never, never>
Creates an `Effect` that succeeds with the provided value.
Use this function to represent a successful computation that yields a value of type `A`.
The effect does not fail and does not require any environmental context.
succeed("Task3").(method) Pipeable.pipe<Effect.Effect<string, never, never>, Effect.Effect<string, never, never>>(this: Effect.Effect<...>, ab: (_: Effect.Effect<string, never, never>) => Effect.Effect<string, never, never>): Effect.Effect<...> (+21 overloads)
pipe(import Effect
Effect.const tap: <string, Effect.Effect<void, never, never>>(f: (a: string) => Effect.Effect<void, never, never>) => <E, R>(self: Effect.Effect<string, E, R>) => Effect.Effect<...> (+7 overloads)
tap(import Console
Console.const log: (...args: ReadonlyArray<any>) => Effect.Effect<void>
log))7]8
9const const program: Effect.Effect<Either<string, string>[], never, never>
program = import Effect
Effect.const all: <(Effect.Effect<string, never, never> | Effect.Effect<never, string, never>)[], {
mode: "either";
}>(arg: (Effect.Effect<string, never, never> | Effect.Effect<never, string, never>)[], options?: {
...;
} | undefined) => Effect.Effect<...>
Runs all the provided effects in sequence respecting the structure provided in input.
Supports multiple arguments, a single argument tuple / array or record / struct.
all(const effects: (Effect.Effect<string, never, never> | Effect.Effect<never, string, never>)[]
effects, { (property) mode: "either"
mode: "either" })10
11import Effect
Effect.const runPromiseExit: <Either<string, string>[], never>(effect: Effect.Effect<Either<string, string>[], never, never>, options?: {
readonly signal?: AbortSignal;
} | undefined) => Promise<...>
Executes an effect and returns a `Promise` that resolves with an `Exit` describing the result.
Use `runPromiseExit` when you need detailed information about the outcome of the effect, including success or failure,
and you want to work with Promises.
runPromiseExit(const program: Effect.Effect<Either<string, string>[], never, never>
program).(method) Promise<Exit<Either<string, string>[], never>>.then<void, never>(onfulfilled?: ((value: Exit<Either<string, string>[], never>) => void | PromiseLike<void>) | null | undefined, onrejected?: ((reason: any) => PromiseLike<...>) | null | undefined): Promise<...>
Attaches callbacks for the resolution and/or rejection of the Promise.
then(namespace console
var console: Console
The `console` module provides a simple debugging console that is similar to the
JavaScript console mechanism provided by web browsers.
The module exports two specific components:
* A `Console` class with methods such as `console.log()`, `console.error()` and `console.warn()` that can be used to write to any Node.js stream.
* A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstdout) and
[`process.stderr`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstderr). The global `console` can be used without importing the `node:console` module.
_**Warning**_: The global console object's methods are neither consistently
synchronous like the browser APIs they resemble, nor are they consistently
asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v22.x/api/process.html#a-note-on-process-io) for
more information.
Example using the global `console`:
```js
console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoops, something bad happened
// at [eval]:5:15
// at Script.runInThisContext (node:vm:132:18)
// at Object.runInThisContext (node:vm:309:38)
// at node:internal/process/execution:77:19
// at [eval]-wrapper:6:22
// at evalScript (node:internal/process/execution:76:60)
// at node:internal/main/eval_string:23:3
const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr
```
Example using the `Console` class:
```js
const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);
myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err
```
console.(method) globalThis.Console.log(message?: any, ...optionalParams: any[]): void
Prints to `stdout` with newline. Multiple arguments can be passed, with the
first used as the primary message and all additional used as substitution
values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html)
(the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args)).
```js
const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout
```
See [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args) for more information.
log)12/*13Output:14Task115Task316{17 _id: 'Exit',18 _tag: 'Success',19 value: [20 { _id: 'Either', _tag: 'Right', right: 'Task1' },21 { _id: 'Either', _tag: 'Left', left: 'Task2: Oh no!' },22 { _id: 'Either', _tag: 'Right', right: 'Task3' }23 ]24}25*/
Similarly, the { mode: "validate" }
option uses Option
to indicate success or failure. Each effect returns None
for success and Some
with the error for failure.
Example (mode: "validate"
)
1import { import Effect
Effect, import Console
Console } from "effect"2
3const const effects: (Effect.Effect<string, never, never> | Effect.Effect<never, string, never>)[]
effects = [4 import Effect
Effect.const succeed: <string>(value: string) => Effect.Effect<string, never, never>
Creates an `Effect` that succeeds with the provided value.
Use this function to represent a successful computation that yields a value of type `A`.
The effect does not fail and does not require any environmental context.
succeed("Task1").(method) Pipeable.pipe<Effect.Effect<string, never, never>, Effect.Effect<string, never, never>>(this: Effect.Effect<...>, ab: (_: Effect.Effect<string, never, never>) => Effect.Effect<string, never, never>): Effect.Effect<...> (+21 overloads)
pipe(import Effect
Effect.const tap: <string, Effect.Effect<void, never, never>>(f: (a: string) => Effect.Effect<void, never, never>) => <E, R>(self: Effect.Effect<string, E, R>) => Effect.Effect<...> (+7 overloads)
tap(import Console
Console.const log: (...args: ReadonlyArray<any>) => Effect.Effect<void>
log)),5 import Effect
Effect.const fail: <string>(error: string) => Effect.Effect<never, string, never>
Creates an `Effect` that represents a recoverable error.
This `Effect` does not succeed but instead fails with the provided error. The
failure can be of any type, and will propagate through the effect pipeline
unless handled.
Use this function when you want to explicitly signal an error in an `Effect`
computation. The failed effect can later be handled with functions like
{@link
catchAll
}
or
{@link
catchTag
}
.
fail("Task2: Oh no!").(method) Pipeable.pipe<Effect.Effect<never, string, never>, Effect.Effect<never, string, never>>(this: Effect.Effect<...>, ab: (_: Effect.Effect<never, string, never>) => Effect.Effect<never, string, never>): Effect.Effect<...> (+21 overloads)
pipe(import Effect
Effect.const tap: <never, Effect.Effect<void, never, never>>(f: (a: never) => Effect.Effect<void, never, never>) => <E, R>(self: Effect.Effect<never, E, R>) => Effect.Effect<...> (+7 overloads)
tap(import Console
Console.const log: (...args: ReadonlyArray<any>) => Effect.Effect<void>
log)),6 import Effect
Effect.const succeed: <string>(value: string) => Effect.Effect<string, never, never>
Creates an `Effect` that succeeds with the provided value.
Use this function to represent a successful computation that yields a value of type `A`.
The effect does not fail and does not require any environmental context.
succeed("Task3").(method) Pipeable.pipe<Effect.Effect<string, never, never>, Effect.Effect<string, never, never>>(this: Effect.Effect<...>, ab: (_: Effect.Effect<string, never, never>) => Effect.Effect<string, never, never>): Effect.Effect<...> (+21 overloads)
pipe(import Effect
Effect.const tap: <string, Effect.Effect<void, never, never>>(f: (a: string) => Effect.Effect<void, never, never>) => <E, R>(self: Effect.Effect<string, E, R>) => Effect.Effect<...> (+7 overloads)
tap(import Console
Console.const log: (...args: ReadonlyArray<any>) => Effect.Effect<void>
log))7]8
9const const program: Effect.Effect<string[], Option<string>[], never>
program = import Effect
Effect.const all: <(Effect.Effect<string, never, never> | Effect.Effect<never, string, never>)[], {
mode: "validate";
}>(arg: (Effect.Effect<string, never, never> | Effect.Effect<never, string, never>)[], options?: {
...;
} | undefined) => Effect.Effect<...>
Runs all the provided effects in sequence respecting the structure provided in input.
Supports multiple arguments, a single argument tuple / array or record / struct.
all(const effects: (Effect.Effect<string, never, never> | Effect.Effect<never, string, never>)[]
effects, { (property) mode: "validate"
mode: "validate" })10
11import Effect
Effect.const runPromiseExit: <string[], Option<string>[]>(effect: Effect.Effect<string[], Option<string>[], never>, options?: {
readonly signal?: AbortSignal;
} | undefined) => Promise<...>
Executes an effect and returns a `Promise` that resolves with an `Exit` describing the result.
Use `runPromiseExit` when you need detailed information about the outcome of the effect, including success or failure,
and you want to work with Promises.
runPromiseExit(const program: Effect.Effect<string[], Option<string>[], never>
program).(method) Promise<Exit<string[], Option<string>[]>>.then<void, never>(onfulfilled?: ((value: Exit<string[], Option<string>[]>) => void | PromiseLike<void>) | null | undefined, onrejected?: ((reason: any) => PromiseLike<never>) | null | undefined): Promise<...>
Attaches callbacks for the resolution and/or rejection of the Promise.
then(((parameter) result: Exit<string[], Option<string>[]>
result) => namespace console
var console: Console
The `console` module provides a simple debugging console that is similar to the
JavaScript console mechanism provided by web browsers.
The module exports two specific components:
* A `Console` class with methods such as `console.log()`, `console.error()` and `console.warn()` that can be used to write to any Node.js stream.
* A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstdout) and
[`process.stderr`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstderr). The global `console` can be used without importing the `node:console` module.
_**Warning**_: The global console object's methods are neither consistently
synchronous like the browser APIs they resemble, nor are they consistently
asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v22.x/api/process.html#a-note-on-process-io) for
more information.
Example using the global `console`:
```js
console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoops, something bad happened
// at [eval]:5:15
// at Script.runInThisContext (node:vm:132:18)
// at Object.runInThisContext (node:vm:309:38)
// at node:internal/process/execution:77:19
// at [eval]-wrapper:6:22
// at evalScript (node:internal/process/execution:76:60)
// at node:internal/main/eval_string:23:3
const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr
```
Example using the `Console` class:
```js
const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);
myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err
```
console.(method) globalThis.Console.log(message?: any, ...optionalParams: any[]): void
Prints to `stdout` with newline. Multiple arguments can be passed, with the
first used as the primary message and all additional used as substitution
values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html)
(the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args)).
```js
const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout
```
See [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args) for more information.
log("%o", (parameter) result: Exit<string[], Option<string>[]>
result))12/*13Output:14Task115Task316{17 _id: 'Exit',18 _tag: 'Failure',19 cause: {20 _id: 'Cause',21 _tag: 'Fail',22 failure: [23 { _id: 'Option', _tag: 'None' },24 { _id: 'Option', _tag: 'Some', value: 'Task2: Oh no!' },25 { _id: 'Option', _tag: 'None' }26 ]27 }28}29*/