Basic Concurrency
Effect provides options to manage how effects are executed, particularly focusing on controlling how many effects run concurrently.
type Options = { readonly concurrency?: Concurrency}
The concurrency
option is used to determine the level of concurrency, with the following values:
type Concurrency = number | "unbounded" | "inherit"
Let’s explore each configuration in detail.
By default, if you don’t specify any concurrency option, effects will run sequentially, one after the other. This means each effect starts only after the previous one completes.
Example (Sequential Execution)
1import { import Effect
Effect, import Duration
Duration } from "effect"2
3// Helper function to simulate a task with a delay4const const makeTask: (n: number, delay: Duration.DurationInput) => Effect.Effect<void, never, never>
makeTask = ((parameter) n: number
n: number, (parameter) delay: Duration.DurationInput
delay: import Duration
Duration.type DurationInput = number | bigint | Duration.Duration | [seconds: number, nanos: number] | `${number} nano` | `${number} nanos` | `${number} micro` | `${number} micros` | `${number} milli` | `${number} millis` | `${number} second` | `${number} seconds` | `${number} minute` | `${number} minutes` | ... 5 more ... | `${number} weeks`
DurationInput) =>5 import Effect
Effect.const promise: <void>(evaluate: (signal: AbortSignal) => PromiseLike<void>) => Effect.Effect<void, never, never>
Creates an `Effect` that represents an asynchronous computation guaranteed to succeed.
The provided function (`thunk`) returns a `Promise` that should never reject.
If the `Promise` does reject, the rejection is treated as a defect.
An optional `AbortSignal` can be provided to allow for interruption of the
wrapped `Promise` API.
promise(6 () =>7 new var Promise: PromiseConstructor
new <void>(executor: (resolve: (value: void | PromiseLike<void>) => void, reject: (reason?: any) => void) => void) => Promise<void>
Creates a new Promise.
Promise<void>(((parameter) resolve: (value: void | PromiseLike<void>) => void
resolve) => {8 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(`start task${(parameter) n: number
n}`) // Logs when the task starts9 function setTimeout<[]>(callback: () => void, ms?: number): NodeJS.Timeout (+1 overload)
namespace setTimeout
Schedules execution of a one-time `callback` after `delay` milliseconds.
The `callback` will likely not be invoked in precisely `delay` milliseconds.
Node.js makes no guarantees about the exact timing of when callbacks will fire,
nor of their ordering. The callback will be called as close as possible to the
time specified.
When `delay` is larger than `2147483647` or less than `1`, the `delay` will be set to `1`. Non-integer delays are truncated to an integer.
If `callback` is not a function, a `TypeError` will be thrown.
This method has a custom variant for promises that is available using `timersPromises.setTimeout()`.
setTimeout(() => {10 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(`task${(parameter) n: number
n} done`) // Logs when the task finishes11 (parameter) resolve: (value: void | PromiseLike<void>) => void
resolve()12 }, import Duration
Duration.const toMillis: (self: Duration.DurationInput) => number
toMillis((parameter) delay: Duration.DurationInput
delay))13 })14 )15
16const const task1: Effect.Effect<void, never, never>
task1 = const makeTask: (n: number, delay: Duration.DurationInput) => Effect.Effect<void, never, never>
makeTask(1, "200 millis")17const const task2: Effect.Effect<void, never, never>
task2 = const makeTask: (n: number, delay: Duration.DurationInput) => Effect.Effect<void, never, never>
makeTask(2, "100 millis")18
19const const sequential: Effect.Effect<[void, void], never, never>
sequential = import Effect
Effect.const all: <readonly [Effect.Effect<void, never, never>, Effect.Effect<void, 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 task1: Effect.Effect<void, never, never>
task1, const task2: Effect.Effect<void, never, never>
task2])20
21import Effect
Effect.const runPromise: <[void, void], never>(effect: Effect.Effect<[void, void], never, never>, options?: {
readonly signal?: AbortSignal;
} | undefined) => Promise<[void, 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 sequential: Effect.Effect<[void, void], never, never>
sequential)22/*23Output:24start task125task1 done26start task2 <-- task2 starts only after task1 completes27task2 done28*/
You can control how many effects run concurrently by setting a number
for concurrency
. For example, concurrency: 2
allows up to two effects to run at the same time.
Example (Limiting to 2 Concurrent Tasks)
1import { import Effect
Effect, import Duration
Duration } from "effect"2
3// Helper function to simulate a task with a delay4const const makeTask: (n: number, delay: Duration.DurationInput) => Effect.Effect<void, never, never>
makeTask = ((parameter) n: number
n: number, (parameter) delay: Duration.DurationInput
delay: import Duration
Duration.type DurationInput = number | bigint | Duration.Duration | [seconds: number, nanos: number] | `${number} nano` | `${number} nanos` | `${number} micro` | `${number} micros` | `${number} milli` | `${number} millis` | `${number} second` | `${number} seconds` | `${number} minute` | `${number} minutes` | ... 5 more ... | `${number} weeks`
DurationInput) =>5 import Effect
Effect.const promise: <void>(evaluate: (signal: AbortSignal) => PromiseLike<void>) => Effect.Effect<void, never, never>
Creates an `Effect` that represents an asynchronous computation guaranteed to succeed.
The provided function (`thunk`) returns a `Promise` that should never reject.
If the `Promise` does reject, the rejection is treated as a defect.
An optional `AbortSignal` can be provided to allow for interruption of the
wrapped `Promise` API.
promise(6 () =>7 new var Promise: PromiseConstructor
new <void>(executor: (resolve: (value: void | PromiseLike<void>) => void, reject: (reason?: any) => void) => void) => Promise<void>
Creates a new Promise.
Promise<void>(((parameter) resolve: (value: void | PromiseLike<void>) => void
resolve) => {8 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(`start task${(parameter) n: number
n}`) // Logs when the task starts9 function setTimeout<[]>(callback: () => void, ms?: number): NodeJS.Timeout (+1 overload)
namespace setTimeout
Schedules execution of a one-time `callback` after `delay` milliseconds.
The `callback` will likely not be invoked in precisely `delay` milliseconds.
Node.js makes no guarantees about the exact timing of when callbacks will fire,
nor of their ordering. The callback will be called as close as possible to the
time specified.
When `delay` is larger than `2147483647` or less than `1`, the `delay` will be set to `1`. Non-integer delays are truncated to an integer.
If `callback` is not a function, a `TypeError` will be thrown.
This method has a custom variant for promises that is available using `timersPromises.setTimeout()`.
setTimeout(() => {10 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(`task${(parameter) n: number
n} done`) // Logs when the task finishes11 (parameter) resolve: (value: void | PromiseLike<void>) => void
resolve()12 }, import Duration
Duration.const toMillis: (self: Duration.DurationInput) => number
toMillis((parameter) delay: Duration.DurationInput
delay))13 })14 )15
16const const task1: Effect.Effect<void, never, never>
task1 = const makeTask: (n: number, delay: Duration.DurationInput) => Effect.Effect<void, never, never>
makeTask(1, "200 millis")17const const task2: Effect.Effect<void, never, never>
task2 = const makeTask: (n: number, delay: Duration.DurationInput) => Effect.Effect<void, never, never>
makeTask(2, "100 millis")18const const task3: Effect.Effect<void, never, never>
task3 = const makeTask: (n: number, delay: Duration.DurationInput) => Effect.Effect<void, never, never>
makeTask(3, "210 millis")19const const task4: Effect.Effect<void, never, never>
task4 = const makeTask: (n: number, delay: Duration.DurationInput) => Effect.Effect<void, never, never>
makeTask(4, "110 millis")20const const task5: Effect.Effect<void, never, never>
task5 = const makeTask: (n: number, delay: Duration.DurationInput) => Effect.Effect<void, never, never>
makeTask(5, "150 millis")21
22const const numbered: Effect.Effect<[void, void, void, void, void], never, never>
numbered = import Effect
Effect.const all: <readonly [Effect.Effect<void, never, never>, Effect.Effect<void, never, never>, Effect.Effect<void, never, never>, Effect.Effect<void, never, never>, Effect.Effect<...>], {
...;
}>(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 task1: Effect.Effect<void, never, never>
task1, const task2: Effect.Effect<void, never, never>
task2, const task3: Effect.Effect<void, never, never>
task3, const task4: Effect.Effect<void, never, never>
task4, const task5: Effect.Effect<void, never, never>
task5], {23 (property) concurrency: number
concurrency: 224})25
26import Effect
Effect.const runPromise: <[void, void, void, void, void], never>(effect: Effect.Effect<[void, void, void, void, void], 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 numbered: Effect.Effect<[void, void, void, void, void], never, never>
numbered)27/*28Output:29start task130start task2 <-- active tasks: task1, task231task2 done32start task3 <-- active tasks: task1, task333task1 done34start task4 <-- active tasks: task3, task435task4 done36start task5 <-- active tasks: task3, task537task3 done38task5 done39*/
When concurrency: "unbounded"
is used, there’s no limit to the number of effects running concurrently.
Example (Unbounded Concurrency)
1import { import Effect
Effect, import Duration
Duration } from "effect"2
3// Helper function to simulate a task with a delay4const const makeTask: (n: number, delay: Duration.DurationInput) => Effect.Effect<void, never, never>
makeTask = ((parameter) n: number
n: number, (parameter) delay: Duration.DurationInput
delay: import Duration
Duration.type DurationInput = number | bigint | Duration.Duration | [seconds: number, nanos: number] | `${number} nano` | `${number} nanos` | `${number} micro` | `${number} micros` | `${number} milli` | `${number} millis` | `${number} second` | `${number} seconds` | `${number} minute` | `${number} minutes` | ... 5 more ... | `${number} weeks`
DurationInput) =>5 import Effect
Effect.const promise: <void>(evaluate: (signal: AbortSignal) => PromiseLike<void>) => Effect.Effect<void, never, never>
Creates an `Effect` that represents an asynchronous computation guaranteed to succeed.
The provided function (`thunk`) returns a `Promise` that should never reject.
If the `Promise` does reject, the rejection is treated as a defect.
An optional `AbortSignal` can be provided to allow for interruption of the
wrapped `Promise` API.
promise(6 () =>7 new var Promise: PromiseConstructor
new <void>(executor: (resolve: (value: void | PromiseLike<void>) => void, reject: (reason?: any) => void) => void) => Promise<void>
Creates a new Promise.
Promise<void>(((parameter) resolve: (value: void | PromiseLike<void>) => void
resolve) => {8 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(`start task${(parameter) n: number
n}`) // Logs when the task starts9 function setTimeout<[]>(callback: () => void, ms?: number): NodeJS.Timeout (+1 overload)
namespace setTimeout
Schedules execution of a one-time `callback` after `delay` milliseconds.
The `callback` will likely not be invoked in precisely `delay` milliseconds.
Node.js makes no guarantees about the exact timing of when callbacks will fire,
nor of their ordering. The callback will be called as close as possible to the
time specified.
When `delay` is larger than `2147483647` or less than `1`, the `delay` will be set to `1`. Non-integer delays are truncated to an integer.
If `callback` is not a function, a `TypeError` will be thrown.
This method has a custom variant for promises that is available using `timersPromises.setTimeout()`.
setTimeout(() => {10 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(`task${(parameter) n: number
n} done`) // Logs when the task finishes11 (parameter) resolve: (value: void | PromiseLike<void>) => void
resolve()12 }, import Duration
Duration.const toMillis: (self: Duration.DurationInput) => number
toMillis((parameter) delay: Duration.DurationInput
delay))13 })14 )15
16const const task1: Effect.Effect<void, never, never>
task1 = const makeTask: (n: number, delay: Duration.DurationInput) => Effect.Effect<void, never, never>
makeTask(1, "200 millis")17const const task2: Effect.Effect<void, never, never>
task2 = const makeTask: (n: number, delay: Duration.DurationInput) => Effect.Effect<void, never, never>
makeTask(2, "100 millis")18const const task3: Effect.Effect<void, never, never>
task3 = const makeTask: (n: number, delay: Duration.DurationInput) => Effect.Effect<void, never, never>
makeTask(3, "210 millis")19const const task4: Effect.Effect<void, never, never>
task4 = const makeTask: (n: number, delay: Duration.DurationInput) => Effect.Effect<void, never, never>
makeTask(4, "110 millis")20const const task5: Effect.Effect<void, never, never>
task5 = const makeTask: (n: number, delay: Duration.DurationInput) => Effect.Effect<void, never, never>
makeTask(5, "150 millis")21
22const const unbounded: Effect.Effect<[void, void, void, void, void], never, never>
unbounded = import Effect
Effect.const all: <readonly [Effect.Effect<void, never, never>, Effect.Effect<void, never, never>, Effect.Effect<void, never, never>, Effect.Effect<void, never, never>, Effect.Effect<...>], {
...;
}>(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 task1: Effect.Effect<void, never, never>
task1, const task2: Effect.Effect<void, never, never>
task2, const task3: Effect.Effect<void, never, never>
task3, const task4: Effect.Effect<void, never, never>
task4, const task5: Effect.Effect<void, never, never>
task5], {23 (property) concurrency: "unbounded"
concurrency: "unbounded"24})25
26import Effect
Effect.const runPromise: <[void, void, void, void, void], never>(effect: Effect.Effect<[void, void, void, void, void], 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 unbounded: Effect.Effect<[void, void, void, void, void], never, never>
unbounded)27/*28Output:29start task130start task231start task332start task433start task534task2 done35task4 done36task5 done37task1 done38task3 done39*/
When using concurrency: "inherit"
, the concurrency level is inherited from the surrounding context. This context can be set using Effect.withConcurrency(number | "unbounded")
. If no context is provided, the default is "unbounded"
.
Example (Inheriting Concurrency from Context)
1import { import Effect
Effect, import Duration
Duration } from "effect"2
3// Helper function to simulate a task with a delay4const const makeTask: (n: number, delay: Duration.DurationInput) => Effect.Effect<void, never, never>
makeTask = ((parameter) n: number
n: number, (parameter) delay: Duration.DurationInput
delay: import Duration
Duration.type DurationInput = number | bigint | Duration.Duration | [seconds: number, nanos: number] | `${number} nano` | `${number} nanos` | `${number} micro` | `${number} micros` | `${number} milli` | `${number} millis` | `${number} second` | `${number} seconds` | `${number} minute` | `${number} minutes` | ... 5 more ... | `${number} weeks`
DurationInput) =>5 import Effect
Effect.const promise: <void>(evaluate: (signal: AbortSignal) => PromiseLike<void>) => Effect.Effect<void, never, never>
Creates an `Effect` that represents an asynchronous computation guaranteed to succeed.
The provided function (`thunk`) returns a `Promise` that should never reject.
If the `Promise` does reject, the rejection is treated as a defect.
An optional `AbortSignal` can be provided to allow for interruption of the
wrapped `Promise` API.
promise(6 () =>7 new var Promise: PromiseConstructor
new <void>(executor: (resolve: (value: void | PromiseLike<void>) => void, reject: (reason?: any) => void) => void) => Promise<void>
Creates a new Promise.
Promise<void>(((parameter) resolve: (value: void | PromiseLike<void>) => void
resolve) => {8 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(`start task${(parameter) n: number
n}`) // Logs when the task starts9 function setTimeout<[]>(callback: () => void, ms?: number): NodeJS.Timeout (+1 overload)
namespace setTimeout
Schedules execution of a one-time `callback` after `delay` milliseconds.
The `callback` will likely not be invoked in precisely `delay` milliseconds.
Node.js makes no guarantees about the exact timing of when callbacks will fire,
nor of their ordering. The callback will be called as close as possible to the
time specified.
When `delay` is larger than `2147483647` or less than `1`, the `delay` will be set to `1`. Non-integer delays are truncated to an integer.
If `callback` is not a function, a `TypeError` will be thrown.
This method has a custom variant for promises that is available using `timersPromises.setTimeout()`.
setTimeout(() => {10 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(`task${(parameter) n: number
n} done`) // Logs when the task finishes11 (parameter) resolve: (value: void | PromiseLike<void>) => void
resolve()12 }, import Duration
Duration.const toMillis: (self: Duration.DurationInput) => number
toMillis((parameter) delay: Duration.DurationInput
delay))13 })14 )15
16const const task1: Effect.Effect<void, never, never>
task1 = const makeTask: (n: number, delay: Duration.DurationInput) => Effect.Effect<void, never, never>
makeTask(1, "200 millis")17const const task2: Effect.Effect<void, never, never>
task2 = const makeTask: (n: number, delay: Duration.DurationInput) => Effect.Effect<void, never, never>
makeTask(2, "100 millis")18const const task3: Effect.Effect<void, never, never>
task3 = const makeTask: (n: number, delay: Duration.DurationInput) => Effect.Effect<void, never, never>
makeTask(3, "210 millis")19const const task4: Effect.Effect<void, never, never>
task4 = const makeTask: (n: number, delay: Duration.DurationInput) => Effect.Effect<void, never, never>
makeTask(4, "110 millis")20const const task5: Effect.Effect<void, never, never>
task5 = const makeTask: (n: number, delay: Duration.DurationInput) => Effect.Effect<void, never, never>
makeTask(5, "150 millis")21
22// Running all tasks with concurrency: "inherit",23// which defaults to "unbounded"24const const inherit: Effect.Effect<[void, void, void, void, void], never, never>
inherit = import Effect
Effect.const all: <readonly [Effect.Effect<void, never, never>, Effect.Effect<void, never, never>, Effect.Effect<void, never, never>, Effect.Effect<void, never, never>, Effect.Effect<...>], {
...;
}>(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 task1: Effect.Effect<void, never, never>
task1, const task2: Effect.Effect<void, never, never>
task2, const task3: Effect.Effect<void, never, never>
task3, const task4: Effect.Effect<void, never, never>
task4, const task5: Effect.Effect<void, never, never>
task5], {25 (property) concurrency: "inherit"
concurrency: "inherit"26})27
28import Effect
Effect.const runPromise: <[void, void, void, void, void], never>(effect: Effect.Effect<[void, void, void, void, void], 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 inherit: Effect.Effect<[void, void, void, void, void], never, never>
inherit)29/*30Output:31start task132start task233start task334start task435start task536task2 done37task4 done38task5 done39task1 done40task3 done41*/
If you use Effect.withConcurrency
, the concurrency configuration will adjust to the specified option.
Example (Setting Concurrency Option)
1import { import Effect
Effect, import Duration
Duration } from "effect"2
3// Helper function to simulate a task with a delay4const const makeTask: (n: number, delay: Duration.DurationInput) => Effect.Effect<void, never, never>
makeTask = ((parameter) n: number
n: number, (parameter) delay: Duration.DurationInput
delay: import Duration
Duration.type DurationInput = number | bigint | Duration.Duration | [seconds: number, nanos: number] | `${number} nano` | `${number} nanos` | `${number} micro` | `${number} micros` | `${number} milli` | `${number} millis` | `${number} second` | `${number} seconds` | `${number} minute` | `${number} minutes` | ... 5 more ... | `${number} weeks`
DurationInput) =>5 import Effect
Effect.const promise: <void>(evaluate: (signal: AbortSignal) => PromiseLike<void>) => Effect.Effect<void, never, never>
Creates an `Effect` that represents an asynchronous computation guaranteed to succeed.
The provided function (`thunk`) returns a `Promise` that should never reject.
If the `Promise` does reject, the rejection is treated as a defect.
An optional `AbortSignal` can be provided to allow for interruption of the
wrapped `Promise` API.
promise(6 () =>7 new var Promise: PromiseConstructor
new <void>(executor: (resolve: (value: void | PromiseLike<void>) => void, reject: (reason?: any) => void) => void) => Promise<void>
Creates a new Promise.
Promise<void>(((parameter) resolve: (value: void | PromiseLike<void>) => void
resolve) => {8 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(`start task${(parameter) n: number
n}`) // Logs when the task starts9 function setTimeout<[]>(callback: () => void, ms?: number): NodeJS.Timeout (+1 overload)
namespace setTimeout
Schedules execution of a one-time `callback` after `delay` milliseconds.
The `callback` will likely not be invoked in precisely `delay` milliseconds.
Node.js makes no guarantees about the exact timing of when callbacks will fire,
nor of their ordering. The callback will be called as close as possible to the
time specified.
When `delay` is larger than `2147483647` or less than `1`, the `delay` will be set to `1`. Non-integer delays are truncated to an integer.
If `callback` is not a function, a `TypeError` will be thrown.
This method has a custom variant for promises that is available using `timersPromises.setTimeout()`.
setTimeout(() => {10 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(`task${(parameter) n: number
n} done`) // Logs when the task finishes11 (parameter) resolve: (value: void | PromiseLike<void>) => void
resolve()12 }, import Duration
Duration.const toMillis: (self: Duration.DurationInput) => number
toMillis((parameter) delay: Duration.DurationInput
delay))13 })14 )15
16const const task1: Effect.Effect<void, never, never>
task1 = const makeTask: (n: number, delay: Duration.DurationInput) => Effect.Effect<void, never, never>
makeTask(1, "200 millis")17const const task2: Effect.Effect<void, never, never>
task2 = const makeTask: (n: number, delay: Duration.DurationInput) => Effect.Effect<void, never, never>
makeTask(2, "100 millis")18const const task3: Effect.Effect<void, never, never>
task3 = const makeTask: (n: number, delay: Duration.DurationInput) => Effect.Effect<void, never, never>
makeTask(3, "210 millis")19const const task4: Effect.Effect<void, never, never>
task4 = const makeTask: (n: number, delay: Duration.DurationInput) => Effect.Effect<void, never, never>
makeTask(4, "110 millis")20const const task5: Effect.Effect<void, never, never>
task5 = const makeTask: (n: number, delay: Duration.DurationInput) => Effect.Effect<void, never, never>
makeTask(5, "150 millis")21
22// Running tasks with concurrency: "inherit",23// which will inherit the surrounding context24const const inherit: Effect.Effect<[void, void, void, void, void], never, never>
inherit = import Effect
Effect.const all: <readonly [Effect.Effect<void, never, never>, Effect.Effect<void, never, never>, Effect.Effect<void, never, never>, Effect.Effect<void, never, never>, Effect.Effect<...>], {
...;
}>(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 task1: Effect.Effect<void, never, never>
task1, const task2: Effect.Effect<void, never, never>
task2, const task3: Effect.Effect<void, never, never>
task3, const task4: Effect.Effect<void, never, never>
task4, const task5: Effect.Effect<void, never, never>
task5], {25 (property) concurrency: "inherit"
concurrency: "inherit"26})27
28// Setting a concurrency limit of 229const const withConcurrency: Effect.Effect<[void, void, void, void, void], never, never>
withConcurrency = const inherit: Effect.Effect<[void, void, void, void, void], never, never>
inherit.(method) Pipeable.pipe<Effect.Effect<[void, void, void, void, void], never, never>, Effect.Effect<[void, void, void, void, void], never, never>>(this: Effect.Effect<...>, ab: (_: Effect.Effect<[void, void, void, void, void], never, never>) => Effect.Effect<...>): Effect.Effect<...> (+21 overloads)
pipe(import Effect
Effect.const withConcurrency: (concurrency: number | "unbounded") => <A, E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R> (+1 overload)
withConcurrency(2))30
31import Effect
Effect.const runPromise: <[void, void, void, void, void], never>(effect: Effect.Effect<[void, void, void, void, void], 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 withConcurrency: Effect.Effect<[void, void, void, void, void], never, never>
withConcurrency)32/*33Output:34start task135start task2 <-- active tasks: task1, task236task2 done37start task3 <-- active tasks: task1, task338task1 done39start task4 <-- active tasks: task3, task440task4 done41start task5 <-- active tasks: task3, task542task3 done43task5 done44*/
All effects in Effect are executed by fibers. If you didn’t create the fiber yourself, it was created by an operation you’re using (if it’s concurrent) or by the Effect runtime system.
A fiber is created any time an effect is run. When running effects concurrently, a fiber is created for each concurrent effect.
To summarize:
- An
Effect
is a higher-level concept that describes an effectful computation. It is lazy and immutable, meaning it represents a computation that may produce a value or fail but does not immediately execute. - A fiber, on the other hand, represents the running execution of an
Effect
. It can be interrupted or awaited to retrieve its result. Think of it as a way to control and interact with the ongoing computation.
Fibers can be interrupted in various ways. Let’s explore some of these scenarios and see examples of how to interrupt fibers in Effect.
A fiber can be interrupted using the Effect.interrupt
effect on that particular fiber.
Example (Without Interruption)
In this case, the program runs without any interruption, logging the start and completion of the task.
1import { import Effect
Effect } from "effect"2
3const const program: Effect.Effect<void, never, never>
program = import Effect
Effect.const gen: <YieldWrap<Effect.Effect<void, never, never>>, void>(f: (resume: Effect.Adapter) => Generator<YieldWrap<Effect.Effect<void, never, never>>, void, never>) => Effect.Effect<...> (+1 overload)
gen(function* () {4 yield* 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("start")5 yield* import Effect
Effect.const sleep: (duration: DurationInput) => Effect.Effect<void>
Returns an effect that suspends for the specified duration. This method is
asynchronous, and does not actually block the fiber executing the effect.
sleep("2 seconds")6 yield* 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("done")7})8
9import Effect
Effect.const runPromiseExit: <void, never>(effect: Effect.Effect<void, never, never>, options?: {
readonly signal?: AbortSignal;
} | undefined) => Promise<Exit<void, never>>
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<void, never, never>
program).(method) Promise<Exit<void, never>>.then<void, never>(onfulfilled?: ((value: Exit<void, never>) => 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)10/*11Output:12timestamp=... level=INFO fiber=#0 message=start13timestamp=... level=INFO fiber=#0 message=done14{ _id: 'Exit', _tag: 'Success', value: undefined }15*/
Example (With Interruption)
Here, the fiber is interrupted after the log "start"
but before the "done"
log. The Effect.interrupt
stops the fiber, and it never reaches the final log.
1import { import Effect
Effect } from "effect"2
3const const program: Effect.Effect<void, never, never>
program = import Effect
Effect.const gen: <YieldWrap<Effect.Effect<void, never, never>>, void>(f: (resume: Effect.Adapter) => Generator<YieldWrap<Effect.Effect<void, never, never>>, void, never>) => Effect.Effect<...> (+1 overload)
gen(function* () {4 yield* 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("start")5 yield* import Effect
Effect.const sleep: (duration: DurationInput) => Effect.Effect<void>
Returns an effect that suspends for the specified duration. This method is
asynchronous, and does not actually block the fiber executing the effect.
sleep("2 seconds")6 yield* import Effect
Effect.const interrupt: Effect.Effect<never, never, never>
interrupt7 yield* 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("done")8})9
10import Effect
Effect.const runPromiseExit: <void, never>(effect: Effect.Effect<void, never, never>, options?: {
readonly signal?: AbortSignal;
} | undefined) => Promise<Exit<void, never>>
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<void, never, never>
program).(method) Promise<Exit<void, never>>.then<void, never>(onfulfilled?: ((value: Exit<void, never>) => 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:13timestamp=... level=INFO fiber=#0 message=start14{15 _id: 'Exit',16 _tag: 'Failure',17 cause: {18 _id: 'Cause',19 _tag: 'Interrupt',20 fiberId: {21 _id: 'FiberId',22 _tag: 'Runtime',23 id: 0,24 startTimeMillis: ...25 }26 }27}28*/
When a fiber is interrupted, the cause of the interruption is captured, including details like the fiber’s ID and when it started.
When running multiple effects concurrently, such as with Effect.forEach
, if one of the effects is interrupted, it causes all concurrent effects to be interrupted as well.
Example (Interrupting Concurrent Effects)
1import { import Effect
Effect } from "effect"2
3const const program: Effect.Effect<void[], never, never>
program = import Effect
Effect.const forEach: <void, never, never, number[]>(self: number[], f: (a: number, i: number) => Effect.Effect<void, 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(4 [1, 2, 3],5 ((parameter) n: number
n) =>6 import Effect
Effect.const gen: <YieldWrap<Effect.Effect<void, never, never>>, void>(f: (resume: Effect.Adapter) => Generator<YieldWrap<Effect.Effect<void, never, never>>, void, never>) => Effect.Effect<...> (+1 overload)
gen(function* () {7 yield* 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(`start #${(parameter) n: number
n}`)8 yield* import Effect
Effect.const sleep: (duration: DurationInput) => Effect.Effect<void>
Returns an effect that suspends for the specified duration. This method is
asynchronous, and does not actually block the fiber executing the effect.
sleep(`${(parameter) n: number
n} seconds`)9 if ((parameter) n: number
n > 1) {10 yield* import Effect
Effect.const interrupt: Effect.Effect<never, never, never>
interrupt11 }12 yield* 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(`done #${(parameter) n: number
n}`)13 }),14 { (property) concurrency?: Concurrency | undefined
concurrency: "unbounded" }15)16
17import Effect
Effect.const runPromiseExit: <void[], never>(effect: Effect.Effect<void[], never, never>, options?: {
readonly signal?: AbortSignal;
} | undefined) => Promise<Exit<void[], never>>
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<void[], never, never>
program).(method) Promise<Exit<void[], never>>.then<void, never>(onfulfilled?: ((value: Exit<void[], never>) => 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) exit: Exit<void[], never>
exit) =>18 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(var JSON: JSON
An intrinsic object that provides functions to convert JavaScript values to and from the JavaScript Object Notation (JSON) format.
JSON.(method) JSON.stringify(value: any, replacer?: (number | string)[] | null, space?: string | number): string (+1 overload)
Converts a JavaScript value to a JavaScript Object Notation (JSON) string.
stringify((parameter) exit: Exit<void[], never>
exit, null, 2))19)20/*21Output:22timestamp=... level=INFO fiber=#1 message="start #1"23timestamp=... level=INFO fiber=#2 message="start #2"24timestamp=... level=INFO fiber=#3 message="start #3"25timestamp=... level=INFO fiber=#1 message="done #1"26{27 "_id": "Exit",28 "_tag": "Failure",29 "cause": {30 "_id": "Cause",31 "_tag": "Parallel",32 "left": {33 "_id": "Cause",34 "_tag": "Interrupt",35 "fiberId": {36 "_id": "FiberId",37 "_tag": "Runtime",38 "id": 3,39 "startTimeMillis": ...40 }41 },42 "right": {43 "_id": "Cause",44 "_tag": "Sequential",45 "left": {46 "_id": "Cause",47 "_tag": "Empty"48 },49 "right": {50 "_id": "Cause",51 "_tag": "Interrupt",52 "fiberId": {53 "_id": "FiberId",54 "_tag": "Runtime",55 "id": 0,56 "startTimeMillis": ...57 }58 }59 }60 }61}62*/
The Effect.race
function allows you to run multiple effects concurrently, returning the result of the first one that successfully completes.
Example (Basic Race Between Effects)
1import { import Effect
Effect } from "effect"2
3const const task1: Effect.Effect<never, string, never>
task1 = import Effect
Effect.const delay: <never, string, never>(self: Effect.Effect<never, string, never>, duration: DurationInput) => Effect.Effect<never, string, never> (+1 overload)
Returns an effect that is delayed from this effect by the specified
`Duration`.
delay(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("task1"), "1 second")4const const task2: Effect.Effect<string, never, never>
task2 = import Effect
Effect.const delay: <string, never, never>(self: Effect.Effect<string, never, never>, duration: DurationInput) => Effect.Effect<string, never, never> (+1 overload)
Returns an effect that is delayed from this effect by the specified
`Duration`.
delay(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("task2"), "2 seconds")5
6// Run both tasks concurrently and return7// the result of the first to complete8const const program: Effect.Effect<string, string, never>
program = import Effect
Effect.const race: <never, string, never, string, never, never>(self: Effect.Effect<never, string, never>, that: Effect.Effect<string, never, never>) => Effect.Effect<string, string, never> (+1 overload)
Returns an effect that races this effect with the specified effect,
returning the first successful `A` from the faster side. If one effect
succeeds, the other will be interrupted. If neither succeeds, then the
effect will fail with some error.
race(const task1: Effect.Effect<never, string, never>
task1, const task2: Effect.Effect<string, never, never>
task2)9
10import Effect
Effect.const runPromise: <string, string>(effect: Effect.Effect<string, string, never>, options?: {
readonly signal?: AbortSignal;
} | undefined) => Promise<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<string, string, never>
program).(method) Promise<string>.then<void, never>(onfulfilled?: ((value: 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)11/*12Output:13task214*/
If you want to handle the result of whichever task completes first, whether it succeeds or fails, you can use the Effect.either
function. This function wraps the result in an Either type, allowing you to see if the result was a success (Right
) or a failure (Left
):
Example (Handling Success or Failure with Either)
1import { import Effect
Effect } from "effect"2
3const const task1: Effect.Effect<never, string, never>
task1 = import Effect
Effect.const delay: <never, string, never>(self: Effect.Effect<never, string, never>, duration: DurationInput) => Effect.Effect<never, string, never> (+1 overload)
Returns an effect that is delayed from this effect by the specified
`Duration`.
delay(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("task1"), "1 second")4const const task2: Effect.Effect<string, never, never>
task2 = import Effect
Effect.const delay: <string, never, never>(self: Effect.Effect<string, never, never>, duration: DurationInput) => Effect.Effect<string, never, never> (+1 overload)
Returns an effect that is delayed from this effect by the specified
`Duration`.
delay(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("task2"), "2 seconds")5
6// Run both tasks concurrently, wrapping the result7// in Either to capture success or failure8const const program: Effect.Effect<Either<never, string> | Either<string, never>, never, never>
program = import Effect
Effect.const race: <Either<never, string>, never, never, Either<string, never>, never, never>(self: Effect.Effect<Either<never, string>, never, never>, that: Effect.Effect<Either<string, never>, never, never>) => Effect.Effect<...> (+1 overload)
Returns an effect that races this effect with the specified effect,
returning the first successful `A` from the faster side. If one effect
succeeds, the other will be interrupted. If neither succeeds, then the
effect will fail with some error.
race(import Effect
Effect.const either: <never, string, never>(self: Effect.Effect<never, string, never>) => Effect.Effect<Either<never, string>, never, never>
Returns an effect whose failure and success have been lifted into an
`Either`. The resulting effect cannot fail, because the failure case has
been exposed as part of the `Either` success case.
This method is useful for recovering from effects that may fail.
The error parameter of the returned `Effect` is `never`, since it is
guaranteed the effect does not model failure.
either(const task1: Effect.Effect<never, string, never>
task1), import Effect
Effect.const either: <string, never, never>(self: Effect.Effect<string, never, never>) => Effect.Effect<Either<string, never>, never, never>
Returns an effect whose failure and success have been lifted into an
`Either`. The resulting effect cannot fail, because the failure case has
been exposed as part of the `Either` success case.
This method is useful for recovering from effects that may fail.
The error parameter of the returned `Effect` is `never`, since it is
guaranteed the effect does not model failure.
either(const task2: Effect.Effect<string, never, never>
task2))9
10import Effect
Effect.const runPromise: <Either<never, string> | Either<string, never>, never>(effect: Effect.Effect<Either<never, string> | Either<string, never>, 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 program: Effect.Effect<Either<never, string> | Either<string, never>, never, never>
program).(method) Promise<Either<never, string> | Either<string, never>>.then<void, never>(onfulfilled?: ((value: Either<never, string> | Either<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) 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{ _id: 'Either', _tag: 'Left', left: 'task1' }14*/