Skip to content

Creating Streams

In this section, we’ll explore various methods for creating Effect Streams. These methods will help you generate streams tailored to your needs.

You can create a pure stream by using the Stream.make constructor. This constructor accepts a variable list of values as its arguments.

import {
import Stream
Stream
,
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
} from "effect"
const
const stream: Stream.Stream<number, never, never>
stream
=
import Stream
Stream
.
const make: <[number, number, number]>(as_0: number, as_1: number, as_2: number) => Stream.Stream<number, never, never>

Creates a stream from an sequence of values.

@example

import { Effect, Stream } from "effect"
const stream = Stream.make(1, 2, 3)
// Effect.runPromise(Stream.runCollect(stream)).then(console.log)
// { _id: 'Chunk', values: [ 1, 2, 3 ] }

@since2.0.0

make
(1, 2, 3)
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
.
const runPromise: <Chunk<number>, never>(effect: Effect.Effect<Chunk<number>, never, never>, options?: {
readonly signal?: AbortSignal;
} | undefined) => Promise<Chunk<number>>

Executes an effect and returns the result as a Promise.

When to Use

Use runPromise when you need to execute an effect and work with the result using Promise syntax, typically for compatibility with other promise-based code.

If the effect succeeds, the promise will resolve with the result. If the effect fails, the promise will reject with an error.

@seerunPromiseExit for a version that returns an Exit type instead of rejecting.

@example

// Title: Running a Successful Effect as a Promise
import { Effect } from "effect"
Effect.runPromise(Effect.succeed(1)).then(console.log)
// Output: 1

@example

//Example: Handling a Failing Effect as a Rejected Promise import { Effect } from "effect"

Effect.runPromise(Effect.fail("my error")).catch(console.error) // Output: // (FiberFailure) Error: my error

@since2.0.0

runPromise
(
import Stream
Stream
.
const runCollect: <number, never, never>(self: Stream.Stream<number, never, never>) => Effect.Effect<Chunk<number>, never, never>

Runs the stream and collects all of its elements to a chunk.

@since2.0.0

runCollect
(
const stream: Stream.Stream<number, never, never>
stream
)).
Promise<Chunk<number>>.then<void, never>(onfulfilled?: ((value: Chunk<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.

@paramonfulfilled The callback to execute when the Promise is resolved.

@paramonrejected The callback to execute when the Promise is rejected.

@returnsA Promise for the completion of which ever callback is executed.

then
(
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 and process.stderr. 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 for more information.

Example using the global console:

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:

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

@seesource

console
.
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) (the arguments are all passed to util.format()).

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() for more information.

@sincev0.1.100

log
)
// { _id: 'Chunk', values: [ 1, 2, 3 ] }

Sometimes, you may require a stream that doesn’t produce any values. In such cases, you can use Stream.empty. This constructor creates a stream that remains empty.

import {
import Stream
Stream
,
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
} from "effect"
const
const stream: Stream.Stream<never, never, never>
stream
=
import Stream
Stream
.
const empty: Stream.Stream<never, never, never>

The empty stream.

@example

import { Effect, Stream } from "effect"
const stream = Stream.empty
// Effect.runPromise(Stream.runCollect(stream)).then(console.log)
// { _id: 'Chunk', values: [] }

@since2.0.0

empty
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
.
const runPromise: <Chunk<never>, never>(effect: Effect.Effect<Chunk<never>, never, never>, options?: {
readonly signal?: AbortSignal;
} | undefined) => Promise<Chunk<never>>

Executes an effect and returns the result as a Promise.

When to Use

Use runPromise when you need to execute an effect and work with the result using Promise syntax, typically for compatibility with other promise-based code.

If the effect succeeds, the promise will resolve with the result. If the effect fails, the promise will reject with an error.

@seerunPromiseExit for a version that returns an Exit type instead of rejecting.

@example

// Title: Running a Successful Effect as a Promise
import { Effect } from "effect"
Effect.runPromise(Effect.succeed(1)).then(console.log)
// Output: 1

@example

//Example: Handling a Failing Effect as a Rejected Promise import { Effect } from "effect"

Effect.runPromise(Effect.fail("my error")).catch(console.error) // Output: // (FiberFailure) Error: my error

@since2.0.0

runPromise
(
import Stream
Stream
.
const runCollect: <never, never, never>(self: Stream.Stream<never, never, never>) => Effect.Effect<Chunk<never>, never, never>

Runs the stream and collects all of its elements to a chunk.

@since2.0.0

runCollect
(
const stream: Stream.Stream<never, never, never>
stream
)).
Promise<Chunk<never>>.then<void, never>(onfulfilled?: ((value: Chunk<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.

@paramonfulfilled The callback to execute when the Promise is resolved.

@paramonrejected The callback to execute when the Promise is rejected.

@returnsA Promise for the completion of which ever callback is executed.

then
(
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 and process.stderr. 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 for more information.

Example using the global console:

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:

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

@seesource

console
.
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) (the arguments are all passed to util.format()).

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() for more information.

@sincev0.1.100

log
)
// { _id: 'Chunk', values: [] }

If you need a stream that contains a single void value, you can use Stream.void. This constructor is handy when you want to represent a stream with a single event or signal.

import {
import Stream
Stream
,
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
} from "effect"
const
const stream: Stream.Stream<void, never, never>
stream
=
import Stream
Stream
.
const void: Stream.Stream<void, never, never>
export void

A stream that contains a single void value.

@example

import { Effect, Stream } from "effect"
const stream = Stream.void
// Effect.runPromise(Stream.runCollect(stream)).then(console.log)
// { _id: 'Chunk', values: [ undefined ] }

@since2.0.0

void
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
.
const runPromise: <Chunk<void>, never>(effect: Effect.Effect<Chunk<void>, never, never>, options?: {
readonly signal?: AbortSignal;
} | undefined) => Promise<Chunk<void>>

Executes an effect and returns the result as a Promise.

When to Use

Use runPromise when you need to execute an effect and work with the result using Promise syntax, typically for compatibility with other promise-based code.

If the effect succeeds, the promise will resolve with the result. If the effect fails, the promise will reject with an error.

@seerunPromiseExit for a version that returns an Exit type instead of rejecting.

@example

// Title: Running a Successful Effect as a Promise
import { Effect } from "effect"
Effect.runPromise(Effect.succeed(1)).then(console.log)
// Output: 1

@example

//Example: Handling a Failing Effect as a Rejected Promise import { Effect } from "effect"

Effect.runPromise(Effect.fail("my error")).catch(console.error) // Output: // (FiberFailure) Error: my error

@since2.0.0

runPromise
(
import Stream
Stream
.
const runCollect: <void, never, never>(self: Stream.Stream<void, never, never>) => Effect.Effect<Chunk<void>, never, never>

Runs the stream and collects all of its elements to a chunk.

@since2.0.0

runCollect
(
const stream: Stream.Stream<void, never, never>
stream
)).
Promise<Chunk<void>>.then<void, never>(onfulfilled?: ((value: Chunk<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.

@paramonfulfilled The callback to execute when the Promise is resolved.

@paramonrejected The callback to execute when the Promise is rejected.

@returnsA Promise for the completion of which ever callback is executed.

then
(
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 and process.stderr. 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 for more information.

Example using the global console:

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:

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

@seesource

console
.
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) (the arguments are all passed to util.format()).

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() for more information.

@sincev0.1.100

log
)
// { _id: 'Chunk', values: [ undefined ] }

To create a stream of integers within a specified range [min, max] (including both endpoints, min and max), you can use Stream.range. This is particularly useful for generating a stream of sequential numbers.

import {
import Stream
Stream
,
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
} from "effect"
// Creating a stream of numbers from 1 to 5
const
const stream: Stream.Stream<number, never, never>
stream
=
import Stream
Stream
.
const range: (min: number, max: number, chunkSize?: number) => Stream.Stream<number>

Constructs a stream from a range of integers, including both endpoints.

@example

import { Effect, Stream } from "effect"
// A Stream with a range of numbers from 1 to 5
const stream = Stream.range(1, 5)
// Effect.runPromise(Stream.runCollect(stream)).then(console.log)
// { _id: 'Chunk', values: [ 1, 2, 3, 4, 5 ] }

@since2.0.0

range
(1, 5)
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
.
const runPromise: <Chunk<number>, never>(effect: Effect.Effect<Chunk<number>, never, never>, options?: {
readonly signal?: AbortSignal;
} | undefined) => Promise<Chunk<number>>

Executes an effect and returns the result as a Promise.

When to Use

Use runPromise when you need to execute an effect and work with the result using Promise syntax, typically for compatibility with other promise-based code.

If the effect succeeds, the promise will resolve with the result. If the effect fails, the promise will reject with an error.

@seerunPromiseExit for a version that returns an Exit type instead of rejecting.

@example

// Title: Running a Successful Effect as a Promise
import { Effect } from "effect"
Effect.runPromise(Effect.succeed(1)).then(console.log)
// Output: 1

@example

//Example: Handling a Failing Effect as a Rejected Promise import { Effect } from "effect"

Effect.runPromise(Effect.fail("my error")).catch(console.error) // Output: // (FiberFailure) Error: my error

@since2.0.0

runPromise
(
import Stream
Stream
.
const runCollect: <number, never, never>(self: Stream.Stream<number, never, never>) => Effect.Effect<Chunk<number>, never, never>

Runs the stream and collects all of its elements to a chunk.

@since2.0.0

runCollect
(
const stream: Stream.Stream<number, never, never>
stream
)).
Promise<Chunk<number>>.then<void, never>(onfulfilled?: ((value: Chunk<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.

@paramonfulfilled The callback to execute when the Promise is resolved.

@paramonrejected The callback to execute when the Promise is rejected.

@returnsA Promise for the completion of which ever callback is executed.

then
(
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 and process.stderr. 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 for more information.

Example using the global console:

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:

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

@seesource

console
.
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) (the arguments are all passed to util.format()).

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() for more information.

@sincev0.1.100

log
)
// { _id: 'Chunk', values: [ 1, 2, 3, 4, 5 ] }

With Stream.iterate, you can generate a stream by applying a function iteratively to an initial value. The initial value becomes the first element produced by the stream, followed by subsequent values produced by f(init), f(f(init)), and so on.

import {
import Stream
Stream
,
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
} from "effect"
// Creating a stream of incrementing numbers
const
const stream: Stream.Stream<number, never, never>
stream
=
import Stream
Stream
.
const iterate: <number>(value: number, next: (value: number) => number) => Stream.Stream<number, never, never>

The infinite stream of iterative function application: a, f(a), f(f(a)), f(f(f(a))), ...

@example

import { Effect, Stream } from "effect"
// An infinite Stream of numbers starting from 1 and incrementing
const stream = Stream.iterate(1, (n) => n + 1)
// Effect.runPromise(Stream.runCollect(stream.pipe(Stream.take(10)))).then(console.log)
// { _id: 'Chunk', values: [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ] }

@since2.0.0

iterate
(1, (
n: number
n
) =>
n: number
n
+ 1) // Produces 1, 2, 3, ...
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
.
const runPromise: <Chunk<number>, never>(effect: Effect.Effect<Chunk<number>, never, never>, options?: {
readonly signal?: AbortSignal;
} | undefined) => Promise<Chunk<number>>

Executes an effect and returns the result as a Promise.

When to Use

Use runPromise when you need to execute an effect and work with the result using Promise syntax, typically for compatibility with other promise-based code.

If the effect succeeds, the promise will resolve with the result. If the effect fails, the promise will reject with an error.

@seerunPromiseExit for a version that returns an Exit type instead of rejecting.

@example

// Title: Running a Successful Effect as a Promise
import { Effect } from "effect"
Effect.runPromise(Effect.succeed(1)).then(console.log)
// Output: 1

@example

//Example: Handling a Failing Effect as a Rejected Promise import { Effect } from "effect"

Effect.runPromise(Effect.fail("my error")).catch(console.error) // Output: // (FiberFailure) Error: my error

@since2.0.0

runPromise
(
import Stream
Stream
.
const runCollect: <number, never, never>(self: Stream.Stream<number, never, never>) => Effect.Effect<Chunk<number>, never, never>

Runs the stream and collects all of its elements to a chunk.

@since2.0.0

runCollect
(
const stream: Stream.Stream<number, never, never>
stream
.
Pipeable.pipe<Stream.Stream<number, never, never>, Stream.Stream<number, never, never>>(this: Stream.Stream<...>, ab: (_: Stream.Stream<number, never, never>) => Stream.Stream<number, never, never>): Stream.Stream<...> (+21 overloads)
pipe
(
import Stream
Stream
.
const take: (n: number) => <A, E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<A, E, R> (+1 overload)

Takes the specified number of elements from this stream.

@example

import { Effect, Stream } from "effect"
const stream = Stream.take(Stream.iterate(0, (n) => n + 1), 5)
// Effect.runPromise(Stream.runCollect(stream)).then(console.log)
// { _id: 'Chunk', values: [ 0, 1, 2, 3, 4 ] }

@since2.0.0

take
(5)))).
Promise<Chunk<number>>.then<void, never>(onfulfilled?: ((value: Chunk<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.

@paramonfulfilled The callback to execute when the Promise is resolved.

@paramonrejected The callback to execute when the Promise is rejected.

@returnsA Promise for the completion of which ever callback is executed.

then
(
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 and process.stderr. 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 for more information.

Example using the global console:

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:

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

@seesource

console
.
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) (the arguments are all passed to util.format()).

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() for more information.

@sincev0.1.100

log
)
// { _id: 'Chunk', values: [ 1, 2, 3, 4, 5 ] }

Stream.scoped is used to create a single-valued stream from a scoped resource. It can be handy when dealing with resources that require explicit acquisition, usage, and release.

import {
import Stream
Stream
,
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
,
import Console
Console
} from "effect"
// Creating a single-valued stream from a scoped resource
const
const stream: Stream.Stream<void, never, never>
stream
=
import Stream
Stream
.
const scoped: <void, never, never>(effect: Effect.Effect<void, never, never>) => Stream.Stream<void, never, never>

Creates a single-valued stream from a scoped resource.

@example

import { Console, Effect, Stream } from "effect"
// Creating a single-valued stream from a scoped resource
const stream = Stream.scoped(
Effect.acquireUseRelease(
Console.log("acquire"),
() => Console.log("use"),
() => Console.log("release")
)
)
// Effect.runPromise(Stream.runCollect(stream)).then(console.log)
// acquire
// use
// release
// { _id: 'Chunk', values: [ undefined ] }

@since2.0.0

scoped
(
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
.
const acquireUseRelease: <void, never, never, void, never, never, void, never>(acquire: Effect.Effect<void, never, never>, use: (a: void) => Effect.Effect<void, never, never>, release: (a: void, exit: Exit<void, never>) => Effect.Effect<...>) => Effect.Effect<...> (+1 overload)

This function is used to ensure that an Effect value that represents the acquisition of a resource (for example, opening a file, launching a thread, etc.) will not be interrupted, and that the resource will always be released when the Effect value completes execution.

acquireUseRelease does the following:

  1. Ensures that the Effect value that acquires the resource will not be interrupted. Note that acquisition may still fail due to internal reasons (such as an uncaught exception).
  2. Ensures that the release Effect value will not be interrupted, and will be executed as long as the acquisition Effect value successfully acquires the resource.

During the time period between the acquisition and release of the resource, the use Effect value will be executed.

If the release Effect value fails, then the entire Effect value will fail, even if the use Effect value succeeds. If this fail-fast behavior is not desired, errors produced by the release Effect value can be caught and ignored.

@since2.0.0

acquireUseRelease
(
import Console
Console
.
const log: (...args: ReadonlyArray<any>) => Effect.Effect<void>

@since2.0.0

log
("acquire"),
() =>
import Console
Console
.
const log: (...args: ReadonlyArray<any>) => Effect.Effect<void>

@since2.0.0

log
("use"),
() =>
import Console
Console
.
const log: (...args: ReadonlyArray<any>) => Effect.Effect<void>

@since2.0.0

log
("release")
)
)
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
.
const runPromise: <Chunk<void>, never>(effect: Effect.Effect<Chunk<void>, never, never>, options?: {
readonly signal?: AbortSignal;
} | undefined) => Promise<Chunk<void>>

Executes an effect and returns the result as a Promise.

When to Use

Use runPromise when you need to execute an effect and work with the result using Promise syntax, typically for compatibility with other promise-based code.

If the effect succeeds, the promise will resolve with the result. If the effect fails, the promise will reject with an error.

@seerunPromiseExit for a version that returns an Exit type instead of rejecting.

@example

// Title: Running a Successful Effect as a Promise
import { Effect } from "effect"
Effect.runPromise(Effect.succeed(1)).then(console.log)
// Output: 1

@example

//Example: Handling a Failing Effect as a Rejected Promise import { Effect } from "effect"

Effect.runPromise(Effect.fail("my error")).catch(console.error) // Output: // (FiberFailure) Error: my error

@since2.0.0

runPromise
(
import Stream
Stream
.
const runCollect: <void, never, never>(self: Stream.Stream<void, never, never>) => Effect.Effect<Chunk<void>, never, never>

Runs the stream and collects all of its elements to a chunk.

@since2.0.0

runCollect
(
const stream: Stream.Stream<void, never, never>
stream
)).
Promise<Chunk<void>>.then<void, never>(onfulfilled?: ((value: Chunk<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.

@paramonfulfilled The callback to execute when the Promise is resolved.

@paramonrejected The callback to execute when the Promise is rejected.

@returnsA Promise for the completion of which ever callback is executed.

then
(
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 and process.stderr. 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 for more information.

Example using the global console:

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:

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

@seesource

console
.
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) (the arguments are all passed to util.format()).

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() for more information.

@sincev0.1.100

log
)
/*
Output:
acquire
use
release
{ _id: 'Chunk', values: [ undefined ] }
*/

Much like the Effect data type, you can generate a Stream using the fail and succeed functions:

import {
import Stream
Stream
,
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
} from "effect"
// Creating a stream that can emit errors
const
const streamWithError: Stream.Stream<never, string, never>
streamWithError
:
import Stream
Stream
.
interface Stream<out A, out E = never, out R = never>

A Stream<A, E, R> is a description of a program that, when evaluated, may emit zero or more values of type A, may fail with errors of type E, and uses an context of type R. One way to think of Stream is as a Effect program that could emit multiple values.

Stream is a purely functional pull based stream. Pull based streams offer inherent laziness and backpressure, relieving users of the need to manage buffers between operators. As an optimization, Stream does not emit single values, but rather an array of values. This allows the cost of effect evaluation to be amortized.

Stream forms a monad on its A type parameter, and has error management facilities for its E type parameter, modeled similarly to Effect (with some adjustments for the multiple-valued nature of Stream). These aspects allow for rich and expressive composition of streams.

@since2.0.0

@since2.0.0

Stream
<never, string> =
import Stream
Stream
.
const fail: <string>(error: string) => Stream.Stream<never, string, never>

Terminates with the specified error.

@example

import { Effect, Stream } from "effect"
const stream = Stream.fail("Uh oh!")
Effect.runPromiseExit(Stream.runCollect(stream)).then(console.log)
// {
// _id: 'Exit',
// _tag: 'Failure',
// cause: { _id: 'Cause', _tag: 'Fail', failure: 'Uh oh!' }
// }

@since2.0.0

fail
("Uh oh!")
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
.
const runPromise: <Chunk<never>, string>(effect: Effect.Effect<Chunk<never>, string, never>, options?: {
readonly signal?: AbortSignal;
} | undefined) => Promise<Chunk<never>>

Executes an effect and returns the result as a Promise.

When to Use

Use runPromise when you need to execute an effect and work with the result using Promise syntax, typically for compatibility with other promise-based code.

If the effect succeeds, the promise will resolve with the result. If the effect fails, the promise will reject with an error.

@seerunPromiseExit for a version that returns an Exit type instead of rejecting.

@example

// Title: Running a Successful Effect as a Promise
import { Effect } from "effect"
Effect.runPromise(Effect.succeed(1)).then(console.log)
// Output: 1

@example

//Example: Handling a Failing Effect as a Rejected Promise import { Effect } from "effect"

Effect.runPromise(Effect.fail("my error")).catch(console.error) // Output: // (FiberFailure) Error: my error

@since2.0.0

runPromise
(
import Stream
Stream
.
const runCollect: <never, string, never>(self: Stream.Stream<never, string, never>) => Effect.Effect<Chunk<never>, string, never>

Runs the stream and collects all of its elements to a chunk.

@since2.0.0

runCollect
(
const streamWithError: Stream.Stream<never, string, never>
streamWithError
))
// throws Error: Uh oh!
// Creating a stream that emits a numeric value
const
const streamWithNumber: Stream.Stream<number, never, never>
streamWithNumber
:
import Stream
Stream
.
interface Stream<out A, out E = never, out R = never>

A Stream<A, E, R> is a description of a program that, when evaluated, may emit zero or more values of type A, may fail with errors of type E, and uses an context of type R. One way to think of Stream is as a Effect program that could emit multiple values.

Stream is a purely functional pull based stream. Pull based streams offer inherent laziness and backpressure, relieving users of the need to manage buffers between operators. As an optimization, Stream does not emit single values, but rather an array of values. This allows the cost of effect evaluation to be amortized.

Stream forms a monad on its A type parameter, and has error management facilities for its E type parameter, modeled similarly to Effect (with some adjustments for the multiple-valued nature of Stream). These aspects allow for rich and expressive composition of streams.

@since2.0.0

@since2.0.0

Stream
<number> =
import Stream
Stream
.
const succeed: <number>(value: number) => Stream.Stream<number, never, never>

Creates a single-valued pure stream.

@example

import { Effect, Stream } from "effect"
// A Stream with a single number
const stream = Stream.succeed(3)
// Effect.runPromise(Stream.runCollect(stream)).then(console.log)
// { _id: 'Chunk', values: [ 3 ] }

@since2.0.0

succeed
(5)
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
.
const runPromise: <Chunk<number>, never>(effect: Effect.Effect<Chunk<number>, never, never>, options?: {
readonly signal?: AbortSignal;
} | undefined) => Promise<Chunk<number>>

Executes an effect and returns the result as a Promise.

When to Use

Use runPromise when you need to execute an effect and work with the result using Promise syntax, typically for compatibility with other promise-based code.

If the effect succeeds, the promise will resolve with the result. If the effect fails, the promise will reject with an error.

@seerunPromiseExit for a version that returns an Exit type instead of rejecting.

@example

// Title: Running a Successful Effect as a Promise
import { Effect } from "effect"
Effect.runPromise(Effect.succeed(1)).then(console.log)
// Output: 1

@example

//Example: Handling a Failing Effect as a Rejected Promise import { Effect } from "effect"

Effect.runPromise(Effect.fail("my error")).catch(console.error) // Output: // (FiberFailure) Error: my error

@since2.0.0

runPromise
(
import Stream
Stream
.
const runCollect: <number, never, never>(self: Stream.Stream<number, never, never>) => Effect.Effect<Chunk<number>, never, never>

Runs the stream and collects all of its elements to a chunk.

@since2.0.0

runCollect
(
const streamWithNumber: Stream.Stream<number, never, never>
streamWithNumber
)).
Promise<Chunk<number>>.then<void, never>(onfulfilled?: ((value: Chunk<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.

@paramonfulfilled The callback to execute when the Promise is resolved.

@paramonrejected The callback to execute when the Promise is rejected.

@returnsA Promise for the completion of which ever callback is executed.

then
(
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 and process.stderr. 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 for more information.

Example using the global console:

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:

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

@seesource

console
.
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) (the arguments are all passed to util.format()).

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() for more information.

@sincev0.1.100

log
)
// { _id: 'Chunk', values: [ 5 ] }

You can construct a stream from a Chunk like this:

import {
import Stream
Stream
,
import Chunk
Chunk
,
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
} from "effect"
// Creating a stream with values from a single Chunk
const
const stream: Stream.Stream<number, never, never>
stream
=
import Stream
Stream
.
const fromChunk: <number>(chunk: Chunk.Chunk<number>) => Stream.Stream<number, never, never>

Creates a stream from a Chunk of values.

@example

import { Chunk, Effect, Stream } from "effect"
// Creating a stream with values from a single Chunk
const stream = Stream.fromChunk(Chunk.make(1, 2, 3))
// Effect.runPromise(Stream.runCollect(stream)).then(console.log)
// { _id: 'Chunk', values: [ 1, 2, 3 ] }

@since2.0.0

fromChunk
(
import Chunk
Chunk
.
const make: <[number, number, number]>(as_0: number, as_1: number, as_2: number) => Chunk.NonEmptyChunk<number>

Builds a NonEmptyChunk from an non-empty collection of elements.

@since2.0.0

make
(1, 2, 3))
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
.
const runPromise: <Chunk.Chunk<number>, never>(effect: Effect.Effect<Chunk.Chunk<number>, never, never>, options?: {
readonly signal?: AbortSignal;
} | undefined) => Promise<...>

Executes an effect and returns the result as a Promise.

When to Use

Use runPromise when you need to execute an effect and work with the result using Promise syntax, typically for compatibility with other promise-based code.

If the effect succeeds, the promise will resolve with the result. If the effect fails, the promise will reject with an error.

@seerunPromiseExit for a version that returns an Exit type instead of rejecting.

@example

// Title: Running a Successful Effect as a Promise
import { Effect } from "effect"
Effect.runPromise(Effect.succeed(1)).then(console.log)
// Output: 1

@example

//Example: Handling a Failing Effect as a Rejected Promise import { Effect } from "effect"

Effect.runPromise(Effect.fail("my error")).catch(console.error) // Output: // (FiberFailure) Error: my error

@since2.0.0

runPromise
(
import Stream
Stream
.
const runCollect: <number, never, never>(self: Stream.Stream<number, never, never>) => Effect.Effect<Chunk.Chunk<number>, never, never>

Runs the stream and collects all of its elements to a chunk.

@since2.0.0

runCollect
(
const stream: Stream.Stream<number, never, never>
stream
)).
Promise<Chunk<number>>.then<void, never>(onfulfilled?: ((value: Chunk.Chunk<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.

@paramonfulfilled The callback to execute when the Promise is resolved.

@paramonrejected The callback to execute when the Promise is rejected.

@returnsA Promise for the completion of which ever callback is executed.

then
(
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 and process.stderr. 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 for more information.

Example using the global console:

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:

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

@seesource

console
.
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) (the arguments are all passed to util.format()).

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() for more information.

@sincev0.1.100

log
)
// { _id: 'Chunk', values: [ 1, 2, 3 ] }

Moreover, you can create a stream from multiple Chunks as well:

import {
import Stream
Stream
,
import Chunk
Chunk
,
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
} from "effect"
// Creating a stream with values from multiple Chunks
const
const stream: Stream.Stream<number, never, never>
stream
=
import Stream
Stream
.
const fromChunks: <number>(...chunks: Chunk.Chunk<number>[]) => Stream.Stream<number, never, never>

Creates a stream from an arbitrary number of chunks.

@example

import { Chunk, Effect, Stream } from "effect"
// Creating a stream with values from multiple Chunks
const stream = Stream.fromChunks(Chunk.make(1, 2, 3), Chunk.make(4, 5, 6))
// Effect.runPromise(Stream.runCollect(stream)).then(console.log)
// { _id: 'Chunk', values: [ 1, 2, 3, 4, 5, 6 ] }

@since2.0.0

fromChunks
(
import Chunk
Chunk
.
const make: <[number, number, number]>(as_0: number, as_1: number, as_2: number) => Chunk.NonEmptyChunk<number>

Builds a NonEmptyChunk from an non-empty collection of elements.

@since2.0.0

make
(1, 2, 3),
import Chunk
Chunk
.
const make: <[number, number, number]>(as_0: number, as_1: number, as_2: number) => Chunk.NonEmptyChunk<number>

Builds a NonEmptyChunk from an non-empty collection of elements.

@since2.0.0

make
(4, 5, 6))
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
.
const runPromise: <Chunk.Chunk<number>, never>(effect: Effect.Effect<Chunk.Chunk<number>, never, never>, options?: {
readonly signal?: AbortSignal;
} | undefined) => Promise<...>

Executes an effect and returns the result as a Promise.

When to Use

Use runPromise when you need to execute an effect and work with the result using Promise syntax, typically for compatibility with other promise-based code.

If the effect succeeds, the promise will resolve with the result. If the effect fails, the promise will reject with an error.

@seerunPromiseExit for a version that returns an Exit type instead of rejecting.

@example

// Title: Running a Successful Effect as a Promise
import { Effect } from "effect"
Effect.runPromise(Effect.succeed(1)).then(console.log)
// Output: 1

@example

//Example: Handling a Failing Effect as a Rejected Promise import { Effect } from "effect"

Effect.runPromise(Effect.fail("my error")).catch(console.error) // Output: // (FiberFailure) Error: my error

@since2.0.0

runPromise
(
import Stream
Stream
.
const runCollect: <number, never, never>(self: Stream.Stream<number, never, never>) => Effect.Effect<Chunk.Chunk<number>, never, never>

Runs the stream and collects all of its elements to a chunk.

@since2.0.0

runCollect
(
const stream: Stream.Stream<number, never, never>
stream
)).
Promise<Chunk<number>>.then<void, never>(onfulfilled?: ((value: Chunk.Chunk<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.

@paramonfulfilled The callback to execute when the Promise is resolved.

@paramonrejected The callback to execute when the Promise is rejected.

@returnsA Promise for the completion of which ever callback is executed.

then
(
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 and process.stderr. 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 for more information.

Example using the global console:

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:

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

@seesource

console
.
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) (the arguments are all passed to util.format()).

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() for more information.

@sincev0.1.100

log
)
// { _id: 'Chunk', values: [ 1, 2, 3, 4, 5, 6 ] }

You can generate a stream from an Effect workflow by employing the Stream.fromEffect constructor. For instance, consider the following stream, which generates a single random number:

import {
import Stream
Stream
,
import Random
Random
,
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
} from "effect"
const
const stream: Stream.Stream<number, never, never>
stream
=
import Stream
Stream
.
const fromEffect: <number, never, never>(effect: Effect.Effect<number, never, never>) => Stream.Stream<number, never, never>

Either emits the success value of this effect or terminates the stream with the failure value of this effect.

@example

import { Effect, Random, Stream } from "effect"
const stream = Stream.fromEffect(Random.nextInt)
// Effect.runPromise(Stream.runCollect(stream)).then(console.log)
// Example Output: { _id: 'Chunk', values: [ 922694024 ] }

@since2.0.0

fromEffect
(
import Random
Random
.
const nextInt: Effect.Effect<number, never, never>

Returns the next integer value from the pseudo-random number generator.

@since2.0.0

nextInt
)
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
.
const runPromise: <Chunk<number>, never>(effect: Effect.Effect<Chunk<number>, never, never>, options?: {
readonly signal?: AbortSignal;
} | undefined) => Promise<Chunk<number>>

Executes an effect and returns the result as a Promise.

When to Use

Use runPromise when you need to execute an effect and work with the result using Promise syntax, typically for compatibility with other promise-based code.

If the effect succeeds, the promise will resolve with the result. If the effect fails, the promise will reject with an error.

@seerunPromiseExit for a version that returns an Exit type instead of rejecting.

@example

// Title: Running a Successful Effect as a Promise
import { Effect } from "effect"
Effect.runPromise(Effect.succeed(1)).then(console.log)
// Output: 1

@example

//Example: Handling a Failing Effect as a Rejected Promise import { Effect } from "effect"

Effect.runPromise(Effect.fail("my error")).catch(console.error) // Output: // (FiberFailure) Error: my error

@since2.0.0

runPromise
(
import Stream
Stream
.
const runCollect: <number, never, never>(self: Stream.Stream<number, never, never>) => Effect.Effect<Chunk<number>, never, never>

Runs the stream and collects all of its elements to a chunk.

@since2.0.0

runCollect
(
const stream: Stream.Stream<number, never, never>
stream
)).
Promise<Chunk<number>>.then<void, never>(onfulfilled?: ((value: Chunk<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.

@paramonfulfilled The callback to execute when the Promise is resolved.

@paramonrejected The callback to execute when the Promise is rejected.

@returnsA Promise for the completion of which ever callback is executed.

then
(
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 and process.stderr. 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 for more information.

Example using the global console:

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:

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

@seesource

console
.
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) (the arguments are all passed to util.format()).

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() for more information.

@sincev0.1.100

log
)
// Example Output: { _id: 'Chunk', values: [ 1042302242 ] }

This method allows you to seamlessly transform the output of an Effect into a stream, providing a straightforward way to work with asynchronous operations within your streams.

Imagine you have an asynchronous function that relies on callbacks. If you want to capture the results emitted by those callbacks as a stream, you can use the Stream.async function. This function is designed to adapt functions that invoke their callbacks multiple times and emit the results as a stream.

Let’s break down how to use it in the following example:

import {
import Stream
Stream
,
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
,
import Chunk
Chunk
,
import Option

@since2.0.0

@since2.0.0

Option
,
import StreamEmit
StreamEmit
} from "effect"
const
const events: number[]
events
= [1, 2, 3, 4]
const
const stream: Stream.Stream<number, never, never>
stream
=
import Stream
Stream
.
async<number, never, never>(register: (emit: StreamEmit.Emit<never, never, number, void>) => void | Effect.Effect<void, never, never>, bufferSize?: number | "unbounded" | {
readonly bufferSize?: number | undefined;
readonly strategy?: "dropping" | "sliding" | "suspend" | undefined;
} | undefined): Stream.Stream<...>
export async

Creates a stream from an asynchronous callback that can be called multiple times. The optionality of the error type E in Emit can be used to signal the end of the stream by setting it to None.

The registration function can optionally return an Effect, which will be executed if the Fiber executing this Effect is interrupted.

@example

import type { StreamEmit } from "effect"
import { Chunk, Effect, Option, Stream } from "effect"
const events = [1, 2, 3, 4]
const stream = Stream.async(
(emit: StreamEmit.Emit<never, never, number, void>) => {
events.forEach((n) => {
setTimeout(() => {
if (n === 3) {
emit(Effect.fail(Option.none())) // Terminate the stream
} else {
emit(Effect.succeed(Chunk.of(n))) // Add the current item to the stream
}
}, 100 * n)
})
}
)
// Effect.runPromise(Stream.runCollect(stream)).then(console.log)
// { _id: 'Chunk', values: [ 1, 2 ] }

@since2.0.0

async
(
(
emit: StreamEmit.Emit<never, never, number, void>
emit
:
import StreamEmit
StreamEmit
.
interface Emit<in R, in E, in A, out B>

An Emit<R, E, A, B> represents an asynchronous callback that can be called multiple times. The callback can be called with a value of type Effect<Chunk<A>, Option<E>, R>, where succeeding with a Chunk<A> indicates to emit those elements, failing with Some<E> indicates to terminate with that error, and failing with None indicates to terminate with an end of stream signal.

@since2.0.0

Emit
<never, never, number, void>) => {
const events: number[]
events
.
Array<number>.forEach(callbackfn: (value: number, index: number, array: number[]) => void, thisArg?: any): void

Performs the specified action for each element in an array.

@paramcallbackfn A function that accepts up to three arguments. forEach calls the callbackfn function one time for each element in the array.

@paramthisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.

forEach
((
n: number
n
) => {
function setTimeout<[]>(callback: () => void, ms?: number): NodeJS.Timeout (+1 overload)

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().

@sincev0.0.1

@paramcallback The function to call when the timer elapses.

@paramdelay The number of milliseconds to wait before calling the callback.

@paramargs Optional arguments to pass when the callback is called.

setTimeout
(() => {
if (
n: number
n
=== 3) {
// Terminate the stream
emit: StreamEmit.Emit
(f: Effect.Effect<Chunk.Chunk<number>, Option.Option<never>, never>) => Promise<void>
emit
(
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
.
const fail: <Option.Option<never>>(error: Option.Option<never>) => Effect.Effect<never, Option.Option<never>, never>

Creates an Effect that represents a recoverable error.

When to Use

Use this function to explicitly signal an error in an Effect. The error will keep propagating unless it is handled. You can handle the error with functions like

catchAll

or

catchTag

.

@seesucceed to create an effect that represents a successful value.

@example

// Title: Creating a Failed Effect
import { Effect } from "effect"
// ┌─── Effect<never, Error, never>
// ▼
const failure = Effect.fail(
new Error("Operation failed due to network error")
)

@since2.0.0

fail
(
import Option

@since2.0.0

@since2.0.0

Option
.
const none: <never>() => Option.Option<never>

Creates a new Option that represents the absence of a value.

@since2.0.0

none
()))
} else {
// Add the current item to the stream
emit: StreamEmit.Emit
(f: Effect.Effect<Chunk.Chunk<number>, Option.Option<never>, never>) => Promise<void>
emit
(
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
.
const succeed: <Chunk.NonEmptyChunk<number>>(value: Chunk.NonEmptyChunk<number>) => Effect.Effect<Chunk.NonEmptyChunk<number>, never, never>

Creates an Effect that always succeeds with a given value.

When to Use

Use this function when you need an effect that completes successfully with a specific value without any errors or external dependencies.

@seefail to create an effect that represents a failure.

@example

// Title: Creating a Successful Effect
import { Effect } from "effect"
// Creating an effect that represents a successful scenario
//
// ┌─── Effect<number, never, never>
// ▼
const success = Effect.succeed(42)

@since2.0.0

succeed
(
import Chunk
Chunk
.
const of: <number>(a: number) => Chunk.NonEmptyChunk<number>

Builds a NonEmptyChunk from a single element.

@since2.0.0

of
(
n: number
n
)))
}
}, 100 *
n: number
n
)
})
}
)
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
.
const runPromise: <Chunk.Chunk<number>, never>(effect: Effect.Effect<Chunk.Chunk<number>, never, never>, options?: {
readonly signal?: AbortSignal;
} | undefined) => Promise<...>

Executes an effect and returns the result as a Promise.

When to Use

Use runPromise when you need to execute an effect and work with the result using Promise syntax, typically for compatibility with other promise-based code.

If the effect succeeds, the promise will resolve with the result. If the effect fails, the promise will reject with an error.

@seerunPromiseExit for a version that returns an Exit type instead of rejecting.

@example

// Title: Running a Successful Effect as a Promise
import { Effect } from "effect"
Effect.runPromise(Effect.succeed(1)).then(console.log)
// Output: 1

@example

//Example: Handling a Failing Effect as a Rejected Promise import { Effect } from "effect"

Effect.runPromise(Effect.fail("my error")).catch(console.error) // Output: // (FiberFailure) Error: my error

@since2.0.0

runPromise
(
import Stream
Stream
.
const runCollect: <number, never, never>(self: Stream.Stream<number, never, never>) => Effect.Effect<Chunk.Chunk<number>, never, never>

Runs the stream and collects all of its elements to a chunk.

@since2.0.0

runCollect
(
const stream: Stream.Stream<number, never, never>
stream
)).
Promise<Chunk<number>>.then<void, never>(onfulfilled?: ((value: Chunk.Chunk<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.

@paramonfulfilled The callback to execute when the Promise is resolved.

@paramonrejected The callback to execute when the Promise is rejected.

@returnsA Promise for the completion of which ever callback is executed.

then
(
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 and process.stderr. 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 for more information.

Example using the global console:

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:

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

@seesource

console
.
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) (the arguments are all passed to util.format()).

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() for more information.

@sincev0.1.100

log
)
// { _id: 'Chunk', values: [ 1, 2 ] }

The StreamEmit.Emit<R, E, A, void> type represents an asynchronous callback that can be called multiple times. This callback takes a value of type Effect<Chunk<A>, Option<E>, R>. Here’s what each of the possible outcomes means:

  • When the value provided to the callback results in a Chunk<A> upon success, it signifies that the specified elements should be emitted as part of the stream.

  • If the value passed to the callback results in a failure with Some<E>, it indicates the termination of the stream with the specified error.

  • When the value passed to the callback results in a failure with None, it serves as a signal for the end of the stream, essentially terminating it.

To put it simply, this type allows you to specify how your asynchronous callback interacts with the stream, determining when to emit elements, when to terminate with an error, or when to signal the end of the stream.

You can create a pure stream from an Iterable of values using the Stream.fromIterable constructor. It’s a straightforward way to convert a collection of values into a stream.

import {
import Stream
Stream
,
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
} from "effect"
const
const numbers: number[]
numbers
= [1, 2, 3]
const
const stream: Stream.Stream<number, never, never>
stream
=
import Stream
Stream
.
const fromIterable: <number>(iterable: Iterable<number>) => Stream.Stream<number, never, never>

Creates a new Stream from an iterable collection of values.

@example

import { Effect, Stream } from "effect"
const numbers = [1, 2, 3]
const stream = Stream.fromIterable(numbers)
// Effect.runPromise(Stream.runCollect(stream)).then(console.log)
// { _id: 'Chunk', values: [ 1, 2, 3 ] }

@since2.0.0

fromIterable
(
const numbers: number[]
numbers
)
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
.
const runPromise: <Chunk<number>, never>(effect: Effect.Effect<Chunk<number>, never, never>, options?: {
readonly signal?: AbortSignal;
} | undefined) => Promise<Chunk<number>>

Executes an effect and returns the result as a Promise.

When to Use

Use runPromise when you need to execute an effect and work with the result using Promise syntax, typically for compatibility with other promise-based code.

If the effect succeeds, the promise will resolve with the result. If the effect fails, the promise will reject with an error.

@seerunPromiseExit for a version that returns an Exit type instead of rejecting.

@example

// Title: Running a Successful Effect as a Promise
import { Effect } from "effect"
Effect.runPromise(Effect.succeed(1)).then(console.log)
// Output: 1

@example

//Example: Handling a Failing Effect as a Rejected Promise import { Effect } from "effect"

Effect.runPromise(Effect.fail("my error")).catch(console.error) // Output: // (FiberFailure) Error: my error

@since2.0.0

runPromise
(
import Stream
Stream
.
const runCollect: <number, never, never>(self: Stream.Stream<number, never, never>) => Effect.Effect<Chunk<number>, never, never>

Runs the stream and collects all of its elements to a chunk.

@since2.0.0

runCollect
(
const stream: Stream.Stream<number, never, never>
stream
)).
Promise<Chunk<number>>.then<void, never>(onfulfilled?: ((value: Chunk<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.

@paramonfulfilled The callback to execute when the Promise is resolved.

@paramonrejected The callback to execute when the Promise is rejected.

@returnsA Promise for the completion of which ever callback is executed.

then
(
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 and process.stderr. 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 for more information.

Example using the global console:

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:

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

@seesource

console
.
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) (the arguments are all passed to util.format()).

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() for more information.

@sincev0.1.100

log
)
// { _id: 'Chunk', values: [ 1, 2, 3 ] }

When you have an effect that produces a value of type Iterable, you can employ the Stream.fromIterableEffect constructor to generate a stream from that effect.

For instance, let’s say you have a database operation that retrieves a list of users. Since this operation involves effects, you can utilize Stream.fromIterableEffect to convert the result into a Stream:

import {
import Stream
Stream
,
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
,
import Context

@since2.0.0

@since2.0.0

Context
} from "effect"
class
class Database
Database
extends
import Context

@since2.0.0

@since2.0.0

Context
.
const Tag: <"Database">(id: "Database") => <Self, Shape>() => Context.TagClass<Self, "Database", Shape>

@example

import { Context, Layer } from "effect"
class MyTag extends Context.Tag("MyTag")<
MyTag,
{ readonly myNum: number }
>() {
static Live = Layer.succeed(this, { myNum: 108 })
}

@since2.0.0

Tag
("Database")<
class Database
Database
,
{ readonly
getUsers: Effect.Effect<string[], never, never>
getUsers
:
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
.
interface Effect<out A, out E = never, out R = never>

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.

@since2.0.0

@since2.0.0

Effect
<
interface Array<T>
Array
<string>> }
>() {}
const
const getUsers: Effect.Effect<string[], never, Database>
getUsers
=
class Database
Database
.
Pipeable.pipe<typeof Database, Effect.Effect<string[], never, Database>>(this: typeof Database, ab: (_: typeof Database) => Effect.Effect<string[], never, Database>): Effect.Effect<...> (+21 overloads)
pipe
(
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
.
const andThen: <{
readonly getUsers: Effect.Effect<Array<string>>;
}, Effect.Effect<string[], never, never>>(f: (a: {
readonly getUsers: Effect.Effect<Array<string>>;
}) => Effect.Effect<string[], never, never>) => <E, R>(self: Effect.Effect<...>) => Effect.Effect<...> (+3 overloads)

Chains two actions, where the second action can depend on the result of the first.

Syntax

const transformedEffect = pipe(myEffect, Effect.andThen(anotherEffect))
// or
const transformedEffect = Effect.andThen(myEffect, anotherEffect)
// or
const transformedEffect = myEffect.pipe(Effect.andThen(anotherEffect))

When to Use

Use andThen when you need to run multiple actions in sequence, with the second action depending on the result of the first. This is useful for combining effects or handling computations that must happen in order.

Details

The second action can be:

  • A constant value (similar to

as

)

  • A function returning a value (similar to

map

)

  • A Promise
  • A function returning a Promise
  • An Effect
  • A function returning an Effect (similar to

flatMap

)

Note: andThen works well with both Option and Either types, treating them as effects.

@example

// Title: Applying a Discount Based on Fetched Amount
import { pipe, Effect } from "effect"
// Function to apply a discount safely to a transaction amount
const applyDiscount = (
total: number,
discountRate: number
): Effect.Effect<number, Error> =>
discountRate === 0
? Effect.fail(new Error("Discount rate cannot be zero"))
: Effect.succeed(total - (total * discountRate) / 100)
// Simulated asynchronous task to fetch a transaction amount from database
const fetchTransactionAmount = Effect.promise(() => Promise.resolve(100))
// Using Effect.map and Effect.flatMap
const result1 = pipe(
fetchTransactionAmount,
Effect.map((amount) => amount * 2),
Effect.flatMap((amount) => applyDiscount(amount, 5))
)
Effect.runPromise(result1).then(console.log)
// Output: 190
// Using Effect.andThen
const result2 = pipe(
fetchTransactionAmount,
Effect.andThen((amount) => amount * 2),
Effect.andThen((amount) => applyDiscount(amount, 5))
)
Effect.runPromise(result2).then(console.log)
// Output: 190

@since2.0.0

andThen
((
_: {
readonly getUsers: Effect.Effect<Array<string>>;
}
_
) =>
_: {
readonly getUsers: Effect.Effect<Array<string>>;
}
_
.
getUsers: Effect.Effect<string[], never, never>
getUsers
))
const
const stream: Stream.Stream<string, never, Database>
stream
=
import Stream
Stream
.
const fromIterableEffect: <string, never, Database>(effect: Effect.Effect<Iterable<string>, never, Database>) => Stream.Stream<string, never, Database>

Creates a stream from an effect producing a value of type Iterable<A>.

@example

import { Context, Effect, Stream } from "effect"
class Database extends Context.Tag("Database")<
Database,
{ readonly getUsers: Effect.Effect<Array<string>> }
>() {}
const getUsers = Database.pipe(Effect.andThen((_) => _.getUsers))
const stream = Stream.fromIterableEffect(getUsers)
// Effect.runPromise(
// Stream.runCollect(stream.pipe(Stream.provideService(Database, { getUsers: Effect.succeed(["user1", "user2"]) })))
// ).then(console.log)
// { _id: 'Chunk', values: [ 'user1', 'user2' ] }

@since2.0.0

fromIterableEffect
(
const getUsers: Effect.Effect<string[], never, Database>
getUsers
)
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
.
const runPromise: <Chunk<string>, never>(effect: Effect.Effect<Chunk<string>, never, never>, options?: {
readonly signal?: AbortSignal;
} | undefined) => Promise<Chunk<string>>

Executes an effect and returns the result as a Promise.

When to Use

Use runPromise when you need to execute an effect and work with the result using Promise syntax, typically for compatibility with other promise-based code.

If the effect succeeds, the promise will resolve with the result. If the effect fails, the promise will reject with an error.

@seerunPromiseExit for a version that returns an Exit type instead of rejecting.

@example

// Title: Running a Successful Effect as a Promise
import { Effect } from "effect"
Effect.runPromise(Effect.succeed(1)).then(console.log)
// Output: 1

@example

//Example: Handling a Failing Effect as a Rejected Promise import { Effect } from "effect"

Effect.runPromise(Effect.fail("my error")).catch(console.error) // Output: // (FiberFailure) Error: my error

@since2.0.0

runPromise
(
import Stream
Stream
.
const runCollect: <string, never, never>(self: Stream.Stream<string, never, never>) => Effect.Effect<Chunk<string>, never, never>

Runs the stream and collects all of its elements to a chunk.

@since2.0.0

runCollect
(
const stream: Stream.Stream<string, never, Database>
stream
.
Pipeable.pipe<Stream.Stream<string, never, Database>, Stream.Stream<string, never, never>>(this: Stream.Stream<...>, ab: (_: Stream.Stream<string, never, Database>) => Stream.Stream<...>): Stream.Stream<...> (+21 overloads)
pipe
(
import Stream
Stream
.
const provideService: <typeof Database>(tag: typeof Database, resource: {
readonly getUsers: Effect.Effect<Array<string>>;
}) => <A, E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<...> (+1 overload)

Provides the stream with the single service it requires. If the stream requires more than one service use Stream.provideContext instead.

@since2.0.0

provideService
(
class Database
Database
, {
getUsers: Effect.Effect<string[], never, never>
getUsers
:
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
.
const succeed: <string[]>(value: string[]) => Effect.Effect<string[], never, never>

Creates an Effect that always succeeds with a given value.

When to Use

Use this function when you need an effect that completes successfully with a specific value without any errors or external dependencies.

@seefail to create an effect that represents a failure.

@example

// Title: Creating a Successful Effect
import { Effect } from "effect"
// Creating an effect that represents a successful scenario
//
// ┌─── Effect<number, never, never>
// ▼
const success = Effect.succeed(42)

@since2.0.0

succeed
(["user1", "user2"])
})
)
)
).
Promise<Chunk<string>>.then<void, never>(onfulfilled?: ((value: Chunk<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.

@paramonfulfilled The callback to execute when the Promise is resolved.

@paramonrejected The callback to execute when the Promise is rejected.

@returnsA Promise for the completion of which ever callback is executed.

then
(
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 and process.stderr. 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 for more information.

Example using the global console:

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:

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

@seesource

console
.
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) (the arguments are all passed to util.format()).

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() for more information.

@sincev0.1.100

log
)
// { _id: 'Chunk', values: [ 'user1', 'user2' ] }

This enables you to work seamlessly with effects and convert their results into streams for further processing.

Async iterables are another type of data source that can be converted into a stream. With the Stream.fromAsyncIterable constructor, you can work with asynchronous data sources and handle potential errors gracefully.

import {
import Stream
Stream
,
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
} from "effect"
const
const myAsyncIterable: () => AsyncGenerator<1 | 2, void, unknown>
myAsyncIterable
= async function* () {
yield 1
yield 2
}
const
const stream: Stream.Stream<1 | 2, Error, never>
stream
=
import Stream
Stream
.
const fromAsyncIterable: <1 | 2, Error>(iterable: AsyncIterable<1 | 2>, onError: (e: unknown) => Error) => Stream.Stream<1 | 2, Error, never>

Creates a stream from an AsyncIterable.

@example

import { Effect, Stream } from "effect"
const myAsyncIterable = async function*() {
yield 1
yield 2
}
const stream = Stream.fromAsyncIterable(
myAsyncIterable(),
(e) => new Error(String(e)) // Error Handling
)
// Effect.runPromise(Stream.runCollect(stream)).then(console.log)
// { _id: 'Chunk', values: [ 1, 2 ] }

@since2.0.0

fromAsyncIterable
(
const myAsyncIterable: () => AsyncGenerator<1 | 2, void, unknown>
myAsyncIterable
(),
(
e: unknown
e
) => new
var Error: ErrorConstructor
new (message?: string) => Error
Error
(
var String: StringConstructor
(value?: any) => string

Allows manipulation and formatting of text strings and determination and location of substrings within strings.

String
(
e: unknown
e
)) // Error Handling
)
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
.
const runPromise: <Chunk<1 | 2>, Error>(effect: Effect.Effect<Chunk<1 | 2>, Error, never>, options?: {
readonly signal?: AbortSignal;
} | undefined) => Promise<...>

Executes an effect and returns the result as a Promise.

When to Use

Use runPromise when you need to execute an effect and work with the result using Promise syntax, typically for compatibility with other promise-based code.

If the effect succeeds, the promise will resolve with the result. If the effect fails, the promise will reject with an error.

@seerunPromiseExit for a version that returns an Exit type instead of rejecting.

@example

// Title: Running a Successful Effect as a Promise
import { Effect } from "effect"
Effect.runPromise(Effect.succeed(1)).then(console.log)
// Output: 1

@example

//Example: Handling a Failing Effect as a Rejected Promise import { Effect } from "effect"

Effect.runPromise(Effect.fail("my error")).catch(console.error) // Output: // (FiberFailure) Error: my error

@since2.0.0

runPromise
(
import Stream
Stream
.
const runCollect: <1 | 2, Error, never>(self: Stream.Stream<1 | 2, Error, never>) => Effect.Effect<Chunk<1 | 2>, Error, never>

Runs the stream and collects all of its elements to a chunk.

@since2.0.0

runCollect
(
const stream: Stream.Stream<1 | 2, Error, never>
stream
)).
Promise<Chunk<1 | 2>>.then<void, never>(onfulfilled?: ((value: Chunk<1 | 2>) => void | PromiseLike<void>) | null | undefined, onrejected?: ((reason: any) => PromiseLike<never>) | null | undefined): Promise<...>

Attaches callbacks for the resolution and/or rejection of the Promise.

@paramonfulfilled The callback to execute when the Promise is resolved.

@paramonrejected The callback to execute when the Promise is rejected.

@returnsA Promise for the completion of which ever callback is executed.

then
(
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 and process.stderr. 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 for more information.

Example using the global console:

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:

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

@seesource

console
.
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) (the arguments are all passed to util.format()).

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() for more information.

@sincev0.1.100

log
)
// { _id: 'Chunk', values: [ 1, 2 ] }

In this code, we define an async iterable and then create a stream named stream from it. Additionally, we provide an error handler function to manage any potential errors that may occur during the conversion.

You can create a stream that endlessly repeats a specific value using the Stream.repeatValue constructor:

import {
import Stream
Stream
,
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
} from "effect"
const
const stream: Stream.Stream<number, never, never>
stream
=
import Stream
Stream
.
const repeatValue: <number>(value: number) => Stream.Stream<number, never, never>

Repeats the provided value infinitely.

@example

import { Effect, Stream } from "effect"
const stream = Stream.repeatValue(0)
// Effect.runPromise(Stream.runCollect(stream.pipe(Stream.take(5)))).then(console.log)
// { _id: 'Chunk', values: [ 0, 0, 0, 0, 0 ] }

@since2.0.0

repeatValue
(0)
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
.
const runPromise: <Chunk<number>, never>(effect: Effect.Effect<Chunk<number>, never, never>, options?: {
readonly signal?: AbortSignal;
} | undefined) => Promise<Chunk<number>>

Executes an effect and returns the result as a Promise.

When to Use

Use runPromise when you need to execute an effect and work with the result using Promise syntax, typically for compatibility with other promise-based code.

If the effect succeeds, the promise will resolve with the result. If the effect fails, the promise will reject with an error.

@seerunPromiseExit for a version that returns an Exit type instead of rejecting.

@example

// Title: Running a Successful Effect as a Promise
import { Effect } from "effect"
Effect.runPromise(Effect.succeed(1)).then(console.log)
// Output: 1

@example

//Example: Handling a Failing Effect as a Rejected Promise import { Effect } from "effect"

Effect.runPromise(Effect.fail("my error")).catch(console.error) // Output: // (FiberFailure) Error: my error

@since2.0.0

runPromise
(
import Stream
Stream
.
const runCollect: <number, never, never>(self: Stream.Stream<number, never, never>) => Effect.Effect<Chunk<number>, never, never>

Runs the stream and collects all of its elements to a chunk.

@since2.0.0

runCollect
(
const stream: Stream.Stream<number, never, never>
stream
.
Pipeable.pipe<Stream.Stream<number, never, never>, Stream.Stream<number, never, never>>(this: Stream.Stream<...>, ab: (_: Stream.Stream<number, never, never>) => Stream.Stream<number, never, never>): Stream.Stream<...> (+21 overloads)
pipe
(
import Stream
Stream
.
const take: (n: number) => <A, E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<A, E, R> (+1 overload)

Takes the specified number of elements from this stream.

@example

import { Effect, Stream } from "effect"
const stream = Stream.take(Stream.iterate(0, (n) => n + 1), 5)
// Effect.runPromise(Stream.runCollect(stream)).then(console.log)
// { _id: 'Chunk', values: [ 0, 1, 2, 3, 4 ] }

@since2.0.0

take
(5)))).
Promise<Chunk<number>>.then<void, never>(onfulfilled?: ((value: Chunk<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.

@paramonfulfilled The callback to execute when the Promise is resolved.

@paramonrejected The callback to execute when the Promise is rejected.

@returnsA Promise for the completion of which ever callback is executed.

then
(
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 and process.stderr. 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 for more information.

Example using the global console:

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:

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

@seesource

console
.
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) (the arguments are all passed to util.format()).

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() for more information.

@sincev0.1.100

log
)
// { _id: 'Chunk', values: [ 0, 0, 0, 0, 0 ] }

Stream.repeat allows you to create a stream that repeats a specified stream’s content according to a schedule. This can be useful for generating recurring events or values.

import {
import Stream
Stream
,
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
,
import Schedule
Schedule
} from "effect"
// Creating a stream that repeats a value indefinitely
const
const stream: Stream.Stream<number, never, never>
stream
=
import Stream
Stream
.
const repeat: <number, never, never, number, never>(self: Stream.Stream<number, never, never>, schedule: Schedule.Schedule<number, unknown, never>) => Stream.Stream<number, never, never> (+1 overload)

Repeats the entire stream using the specified schedule. The stream will execute normally, and then repeat again according to the provided schedule.

@example

import { Effect, Schedule, Stream } from "effect"
const stream = Stream.repeat(Stream.succeed(1), Schedule.forever)
// Effect.runPromise(Stream.runCollect(stream.pipe(Stream.take(5)))).then(console.log)
// { _id: 'Chunk', values: [ 1, 1, 1, 1, 1 ] }

@since2.0.0

repeat
(
import Stream
Stream
.
const succeed: <number>(value: number) => Stream.Stream<number, never, never>

Creates a single-valued pure stream.

@example

import { Effect, Stream } from "effect"
// A Stream with a single number
const stream = Stream.succeed(3)
// Effect.runPromise(Stream.runCollect(stream)).then(console.log)
// { _id: 'Chunk', values: [ 3 ] }

@since2.0.0

succeed
(1),
import Schedule
Schedule
.
const forever: Schedule.Schedule<number, unknown, never>

A schedule that always recurs, producing a count of repeats: 0, 1, 2.

@since2.0.0

forever
)
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
.
const runPromise: <Chunk<number>, never>(effect: Effect.Effect<Chunk<number>, never, never>, options?: {
readonly signal?: AbortSignal;
} | undefined) => Promise<Chunk<number>>

Executes an effect and returns the result as a Promise.

When to Use

Use runPromise when you need to execute an effect and work with the result using Promise syntax, typically for compatibility with other promise-based code.

If the effect succeeds, the promise will resolve with the result. If the effect fails, the promise will reject with an error.

@seerunPromiseExit for a version that returns an Exit type instead of rejecting.

@example

// Title: Running a Successful Effect as a Promise
import { Effect } from "effect"
Effect.runPromise(Effect.succeed(1)).then(console.log)
// Output: 1

@example

//Example: Handling a Failing Effect as a Rejected Promise import { Effect } from "effect"

Effect.runPromise(Effect.fail("my error")).catch(console.error) // Output: // (FiberFailure) Error: my error

@since2.0.0

runPromise
(
import Stream
Stream
.
const runCollect: <number, never, never>(self: Stream.Stream<number, never, never>) => Effect.Effect<Chunk<number>, never, never>

Runs the stream and collects all of its elements to a chunk.

@since2.0.0

runCollect
(
const stream: Stream.Stream<number, never, never>
stream
.
Pipeable.pipe<Stream.Stream<number, never, never>, Stream.Stream<number, never, never>>(this: Stream.Stream<...>, ab: (_: Stream.Stream<number, never, never>) => Stream.Stream<number, never, never>): Stream.Stream<...> (+21 overloads)
pipe
(
import Stream
Stream
.
const take: (n: number) => <A, E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<A, E, R> (+1 overload)

Takes the specified number of elements from this stream.

@example

import { Effect, Stream } from "effect"
const stream = Stream.take(Stream.iterate(0, (n) => n + 1), 5)
// Effect.runPromise(Stream.runCollect(stream)).then(console.log)
// { _id: 'Chunk', values: [ 0, 1, 2, 3, 4 ] }

@since2.0.0

take
(5)))).
Promise<Chunk<number>>.then<void, never>(onfulfilled?: ((value: Chunk<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.

@paramonfulfilled The callback to execute when the Promise is resolved.

@paramonrejected The callback to execute when the Promise is rejected.

@returnsA Promise for the completion of which ever callback is executed.

then
(
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 and process.stderr. 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 for more information.

Example using the global console:

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:

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

@seesource

console
.
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) (the arguments are all passed to util.format()).

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() for more information.

@sincev0.1.100

log
)
// { _id: 'Chunk', values: [ 1, 1, 1, 1, 1 ] }

Imagine you have an effectful API call, and you want to use the result of that call to create a stream. You can achieve this by creating a stream from the effect and repeating it indefinitely.

Here’s an example of generating a stream of random numbers:

import {
import Stream
Stream
,
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
,
import Random
Random
} from "effect"
const
const stream: Stream.Stream<number, never, never>
stream
=
import Stream
Stream
.
const repeatEffect: <number, never, never>(effect: Effect.Effect<number, never, never>) => Stream.Stream<number, never, never>

Creates a stream from an effect producing a value of type A which repeats forever.

@example

import { Effect, Random, Stream } from "effect"
const stream = Stream.repeatEffect(Random.nextInt)
// Effect.runPromise(Stream.runCollect(stream.pipe(Stream.take(5)))).then(console.log)
// Example Output: { _id: 'Chunk', values: [ 3891571149, 4239494205, 2352981603, 2339111046, 1488052210 ] }

@since2.0.0

repeatEffect
(
import Random
Random
.
const nextInt: Effect.Effect<number, never, never>

Returns the next integer value from the pseudo-random number generator.

@since2.0.0

nextInt
)
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
.
const runPromise: <Chunk<number>, never>(effect: Effect.Effect<Chunk<number>, never, never>, options?: {
readonly signal?: AbortSignal;
} | undefined) => Promise<Chunk<number>>

Executes an effect and returns the result as a Promise.

When to Use

Use runPromise when you need to execute an effect and work with the result using Promise syntax, typically for compatibility with other promise-based code.

If the effect succeeds, the promise will resolve with the result. If the effect fails, the promise will reject with an error.

@seerunPromiseExit for a version that returns an Exit type instead of rejecting.

@example

// Title: Running a Successful Effect as a Promise
import { Effect } from "effect"
Effect.runPromise(Effect.succeed(1)).then(console.log)
// Output: 1

@example

//Example: Handling a Failing Effect as a Rejected Promise import { Effect } from "effect"

Effect.runPromise(Effect.fail("my error")).catch(console.error) // Output: // (FiberFailure) Error: my error

@since2.0.0

runPromise
(
import Stream
Stream
.
const runCollect: <number, never, never>(self: Stream.Stream<number, never, never>) => Effect.Effect<Chunk<number>, never, never>

Runs the stream and collects all of its elements to a chunk.

@since2.0.0

runCollect
(
const stream: Stream.Stream<number, never, never>
stream
.
Pipeable.pipe<Stream.Stream<number, never, never>, Stream.Stream<number, never, never>>(this: Stream.Stream<...>, ab: (_: Stream.Stream<number, never, never>) => Stream.Stream<number, never, never>): Stream.Stream<...> (+21 overloads)
pipe
(
import Stream
Stream
.
const take: (n: number) => <A, E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<A, E, R> (+1 overload)

Takes the specified number of elements from this stream.

@example

import { Effect, Stream } from "effect"
const stream = Stream.take(Stream.iterate(0, (n) => n + 1), 5)
// Effect.runPromise(Stream.runCollect(stream)).then(console.log)
// { _id: 'Chunk', values: [ 0, 1, 2, 3, 4 ] }

@since2.0.0

take
(5)))).
Promise<Chunk<number>>.then<void, never>(onfulfilled?: ((value: Chunk<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.

@paramonfulfilled The callback to execute when the Promise is resolved.

@paramonrejected The callback to execute when the Promise is rejected.

@returnsA Promise for the completion of which ever callback is executed.

then
(
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 and process.stderr. 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 for more information.

Example using the global console:

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:

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

@seesource

console
.
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) (the arguments are all passed to util.format()).

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() for more information.

@sincev0.1.100

log
)
/*
Example Output:
{
_id: 'Chunk',
values: [ 1666935266, 604851965, 2194299958, 3393707011, 4090317618 ]
}
*/

You can repeatedly evaluate a given effect and terminate the stream based on specific conditions.

In this example, we’re draining an Iterator to create a stream from it:

import {
import Stream
Stream
,
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
,
import Option

@since2.0.0

@since2.0.0

Option
} from "effect"
const
const drainIterator: <A>(it: Iterator<A>) => Stream.Stream<A>
drainIterator
= <
function (type parameter) A in <A>(it: Iterator<A>): Stream.Stream<A>
A
>(
it: Iterator<A, any, any>
it
:
interface Iterator<T, TReturn = any, TNext = any>
Iterator
<
function (type parameter) A in <A>(it: Iterator<A>): Stream.Stream<A>
A
>):
import Stream
Stream
.
interface Stream<out A, out E = never, out R = never>

A Stream<A, E, R> is a description of a program that, when evaluated, may emit zero or more values of type A, may fail with errors of type E, and uses an context of type R. One way to think of Stream is as a Effect program that could emit multiple values.

Stream is a purely functional pull based stream. Pull based streams offer inherent laziness and backpressure, relieving users of the need to manage buffers between operators. As an optimization, Stream does not emit single values, but rather an array of values. This allows the cost of effect evaluation to be amortized.

Stream forms a monad on its A type parameter, and has error management facilities for its E type parameter, modeled similarly to Effect (with some adjustments for the multiple-valued nature of Stream). These aspects allow for rich and expressive composition of streams.

@since2.0.0

@since2.0.0

Stream
<
function (type parameter) A in <A>(it: Iterator<A>): Stream.Stream<A>
A
> =>
import Stream
Stream
.
const repeatEffectOption: <A, never, never>(effect: Effect.Effect<A, Option.Option<never>, never>) => Stream.Stream<A, never, never>

Creates a stream from an effect producing values of type A until it fails with None.

@example

// In this example, we're draining an Iterator to create a stream from it
import { Stream, Effect, Option } from "effect"
const drainIterator = <A>(it: Iterator<A>): Stream.Stream<A> =>
Stream.repeatEffectOption(
Effect.sync(() => it.next()).pipe(
Effect.andThen((res) => {
if (res.done) {
return Effect.fail(Option.none())
}
return Effect.succeed(res.value)
})
)
)

@since2.0.0

repeatEffectOption
(
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
.
const sync: <IteratorResult<A, any>>(thunk: LazyArg<IteratorResult<A, any>>) => Effect.Effect<IteratorResult<A, any>, never, never>

Creates an Effect that represents a synchronous side-effectful computation.

When to Use

Use sync when you are sure the operation will not fail.

Details

The provided function (thunk) must not throw errors; if it does, the error will be treated as a "defect".

This defect is not a standard error but indicates a flaw in the logic that was expected to be error-free. You can think of it similar to an unexpected crash in the program, which can be further managed or logged using tools like

catchAllDefect

.

@seetry_try for a version that can handle failures.

@example

// Title: Logging a Message
import { Effect } from "effect"
const log = (message: string) =>
Effect.sync(() => {
console.log(message) // side effect
})
// ┌─── Effect<void, never, never>
// ▼
const program = log("Hello, World!")

@since2.0.0

sync
(() =>
it: Iterator<A, any, any>
it
.
Iterator<A, any, any>.next(...[value]: [] | [any]): IteratorResult<A, any>
next
()).
Pipeable.pipe<Effect.Effect<IteratorResult<A, any>, never, never>, Effect.Effect<A, Option.Option<never>, never>>(this: Effect.Effect<...>, ab: (_: Effect.Effect<IteratorResult<A, any>, never, never>) => Effect.Effect<...>): Effect.Effect<...> (+21 overloads)
pipe
(
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
.
const andThen: <IteratorResult<A, any>, Effect.Effect<never, Option.Option<never>, never> | Effect.Effect<A, never, never>>(f: (a: IteratorResult<A, any>) => Effect.Effect<...> | Effect.Effect<...>) => <E, R>(self: Effect.Effect<...>) => Effect.Effect<...> (+3 overloads)

Chains two actions, where the second action can depend on the result of the first.

Syntax

const transformedEffect = pipe(myEffect, Effect.andThen(anotherEffect))
// or
const transformedEffect = Effect.andThen(myEffect, anotherEffect)
// or
const transformedEffect = myEffect.pipe(Effect.andThen(anotherEffect))

When to Use

Use andThen when you need to run multiple actions in sequence, with the second action depending on the result of the first. This is useful for combining effects or handling computations that must happen in order.

Details

The second action can be:

  • A constant value (similar to

as

)

  • A function returning a value (similar to

map

)

  • A Promise
  • A function returning a Promise
  • An Effect
  • A function returning an Effect (similar to

flatMap

)

Note: andThen works well with both Option and Either types, treating them as effects.

@example

// Title: Applying a Discount Based on Fetched Amount
import { pipe, Effect } from "effect"
// Function to apply a discount safely to a transaction amount
const applyDiscount = (
total: number,
discountRate: number
): Effect.Effect<number, Error> =>
discountRate === 0
? Effect.fail(new Error("Discount rate cannot be zero"))
: Effect.succeed(total - (total * discountRate) / 100)
// Simulated asynchronous task to fetch a transaction amount from database
const fetchTransactionAmount = Effect.promise(() => Promise.resolve(100))
// Using Effect.map and Effect.flatMap
const result1 = pipe(
fetchTransactionAmount,
Effect.map((amount) => amount * 2),
Effect.flatMap((amount) => applyDiscount(amount, 5))
)
Effect.runPromise(result1).then(console.log)
// Output: 190
// Using Effect.andThen
const result2 = pipe(
fetchTransactionAmount,
Effect.andThen((amount) => amount * 2),
Effect.andThen((amount) => applyDiscount(amount, 5))
)
Effect.runPromise(result2).then(console.log)
// Output: 190

@since2.0.0

andThen
((
res: IteratorResult<A, any>
res
) => {
if (
res: IteratorResult<A, any>
res
.
done?: boolean | undefined
done
) {
return
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
.
const fail: <Option.Option<never>>(error: Option.Option<never>) => Effect.Effect<never, Option.Option<never>, never>

Creates an Effect that represents a recoverable error.

When to Use

Use this function to explicitly signal an error in an Effect. The error will keep propagating unless it is handled. You can handle the error with functions like

catchAll

or

catchTag

.

@seesucceed to create an effect that represents a successful value.

@example

// Title: Creating a Failed Effect
import { Effect } from "effect"
// ┌─── Effect<never, Error, never>
// ▼
const failure = Effect.fail(
new Error("Operation failed due to network error")
)

@since2.0.0

fail
(
import Option

@since2.0.0

@since2.0.0

Option
.
const none: <never>() => Option.Option<never>

Creates a new Option that represents the absence of a value.

@since2.0.0

none
())
}
return
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
.
const succeed: <A>(value: A) => Effect.Effect<A, never, never>

Creates an Effect that always succeeds with a given value.

When to Use

Use this function when you need an effect that completes successfully with a specific value without any errors or external dependencies.

@seefail to create an effect that represents a failure.

@example

// Title: Creating a Successful Effect
import { Effect } from "effect"
// Creating an effect that represents a successful scenario
//
// ┌─── Effect<number, never, never>
// ▼
const success = Effect.succeed(42)

@since2.0.0

succeed
(
res: IteratorYieldResult<A>
res
.
IteratorYieldResult<A>.value: A
value
)
})
)
)

You can create a stream that emits void values at specified intervals using the Stream.tick constructor. This is useful for creating periodic events.

import {
import Stream
Stream
,
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
} from "effect"
const
const stream: Stream.Stream<void, never, never>
stream
=
import Stream
Stream
.
const tick: (interval: DurationInput) => Stream.Stream<void>

A stream that emits void values spaced by the specified duration.

@example

import { Effect, Stream } from "effect"
let last = Date.now()
const log = (message: string) =>
Effect.sync(() => {
const end = Date.now()
console.log(`${message} after ${end - last}ms`)
last = end
})
const stream = Stream.tick("1 seconds").pipe(Stream.tap(() => log("tick")))
// Effect.runPromise(Stream.runCollect(stream.pipe(Stream.take(5)))).then(console.log)
// tick after 4ms
// tick after 1003ms
// tick after 1001ms
// tick after 1002ms
// tick after 1002ms
// { _id: 'Chunk', values: [ undefined, undefined, undefined, undefined, undefined ] }

@since2.0.0

tick
("100 millis")
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
.
const runPromise: <Chunk<void>, never>(effect: Effect.Effect<Chunk<void>, never, never>, options?: {
readonly signal?: AbortSignal;
} | undefined) => Promise<Chunk<void>>

Executes an effect and returns the result as a Promise.

When to Use

Use runPromise when you need to execute an effect and work with the result using Promise syntax, typically for compatibility with other promise-based code.

If the effect succeeds, the promise will resolve with the result. If the effect fails, the promise will reject with an error.

@seerunPromiseExit for a version that returns an Exit type instead of rejecting.

@example

// Title: Running a Successful Effect as a Promise
import { Effect } from "effect"
Effect.runPromise(Effect.succeed(1)).then(console.log)
// Output: 1

@example

//Example: Handling a Failing Effect as a Rejected Promise import { Effect } from "effect"

Effect.runPromise(Effect.fail("my error")).catch(console.error) // Output: // (FiberFailure) Error: my error

@since2.0.0

runPromise
(
import Stream
Stream
.
const runCollect: <void, never, never>(self: Stream.Stream<void, never, never>) => Effect.Effect<Chunk<void>, never, never>

Runs the stream and collects all of its elements to a chunk.

@since2.0.0

runCollect
(
const stream: Stream.Stream<void, never, never>
stream
.
Pipeable.pipe<Stream.Stream<void, never, never>, Stream.Stream<void, never, never>>(this: Stream.Stream<...>, ab: (_: Stream.Stream<void, never, never>) => Stream.Stream<void, never, never>): Stream.Stream<...> (+21 overloads)
pipe
(
import Stream
Stream
.
const take: (n: number) => <A, E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<A, E, R> (+1 overload)

Takes the specified number of elements from this stream.

@example

import { Effect, Stream } from "effect"
const stream = Stream.take(Stream.iterate(0, (n) => n + 1), 5)
// Effect.runPromise(Stream.runCollect(stream)).then(console.log)
// { _id: 'Chunk', values: [ 0, 1, 2, 3, 4 ] }

@since2.0.0

take
(5)))).
Promise<Chunk<void>>.then<void, never>(onfulfilled?: ((value: Chunk<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.

@paramonfulfilled The callback to execute when the Promise is resolved.

@paramonrejected The callback to execute when the Promise is rejected.

@returnsA Promise for the completion of which ever callback is executed.

then
(
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 and process.stderr. 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 for more information.

Example using the global console:

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:

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

@seesource

console
.
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) (the arguments are all passed to util.format()).

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() for more information.

@sincev0.1.100

log
)
/*
Output:
{
_id: 'Chunk',
values: [ undefined, undefined, undefined, undefined, undefined ]
}
*/

In functional programming, the concept of unfold can be thought of as the counterpart to fold.

With fold, we process a data structure and produce a return value. For example, we can take an Array<number> and calculate the sum of its elements.

On the other hand, unfold represents an operation where we start with an initial value and generate a recursive data structure, adding one element at a time using a specified state function. For example, we can create a sequence of natural numbers starting from 1 and using the increment function as the state function.

The Stream module includes an unfold function defined as follows:

declare const unfold: <S, A>(
initialState: S,
step: (s: S) => Option.Option<readonly [A, S]>
) => Stream<A>

Here’s how it works:

  • initialState. This is the initial state value.
  • step. The state function step takes the current state s as input. If the result of this function is None, the stream ends. If it’s Some<[A, S]>, the next element in the stream is A, and the state S is updated for the next step process.

For example, let’s create a stream of natural numbers using Stream.unfold:

import {
import Stream
Stream
,
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
,
import Option

@since2.0.0

@since2.0.0

Option
} from "effect"
const
const stream: Stream.Stream<number, never, never>
stream
=
import Stream
Stream
.
const unfold: <number, number>(s: number, f: (s: number) => Option.Option<readonly [number, number]>) => Stream.Stream<number, never, never>

Creates a stream by peeling off the "layers" of a value of type S.

@example

import { Effect, Option, Stream } from "effect"
const stream = Stream.unfold(1, (n) => Option.some([n, n + 1]))
// Effect.runPromise(Stream.runCollect(stream.pipe(Stream.take(5)))).then(console.log)
// { _id: 'Chunk', values: [ 1, 2, 3, 4, 5 ] }

@since2.0.0

unfold
(1, (
n: number
n
) =>
import Option

@since2.0.0

@since2.0.0

Option
.
const some: <[number, number]>(value: [number, number]) => Option.Option<[number, number]>

Creates a new Option that wraps the given value.

@paramvalue - The value to wrap.

@since2.0.0

some
([
n: number
n
,
n: number
n
+ 1]))
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
.
const runPromise: <Chunk<number>, never>(effect: Effect.Effect<Chunk<number>, never, never>, options?: {
readonly signal?: AbortSignal;
} | undefined) => Promise<Chunk<number>>

Executes an effect and returns the result as a Promise.

When to Use

Use runPromise when you need to execute an effect and work with the result using Promise syntax, typically for compatibility with other promise-based code.

If the effect succeeds, the promise will resolve with the result. If the effect fails, the promise will reject with an error.

@seerunPromiseExit for a version that returns an Exit type instead of rejecting.

@example

// Title: Running a Successful Effect as a Promise
import { Effect } from "effect"
Effect.runPromise(Effect.succeed(1)).then(console.log)
// Output: 1

@example

//Example: Handling a Failing Effect as a Rejected Promise import { Effect } from "effect"

Effect.runPromise(Effect.fail("my error")).catch(console.error) // Output: // (FiberFailure) Error: my error

@since2.0.0

runPromise
(
import Stream
Stream
.
const runCollect: <number, never, never>(self: Stream.Stream<number, never, never>) => Effect.Effect<Chunk<number>, never, never>

Runs the stream and collects all of its elements to a chunk.

@since2.0.0

runCollect
(
const stream: Stream.Stream<number, never, never>
stream
.
Pipeable.pipe<Stream.Stream<number, never, never>, Stream.Stream<number, never, never>>(this: Stream.Stream<...>, ab: (_: Stream.Stream<number, never, never>) => Stream.Stream<number, never, never>): Stream.Stream<...> (+21 overloads)
pipe
(
import Stream
Stream
.
const take: (n: number) => <A, E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<A, E, R> (+1 overload)

Takes the specified number of elements from this stream.

@example

import { Effect, Stream } from "effect"
const stream = Stream.take(Stream.iterate(0, (n) => n + 1), 5)
// Effect.runPromise(Stream.runCollect(stream)).then(console.log)
// { _id: 'Chunk', values: [ 0, 1, 2, 3, 4 ] }

@since2.0.0

take
(5)))).
Promise<Chunk<number>>.then<void, never>(onfulfilled?: ((value: Chunk<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.

@paramonfulfilled The callback to execute when the Promise is resolved.

@paramonrejected The callback to execute when the Promise is rejected.

@returnsA Promise for the completion of which ever callback is executed.

then
(
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 and process.stderr. 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 for more information.

Example using the global console:

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:

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

@seesource

console
.
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) (the arguments are all passed to util.format()).

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() for more information.

@sincev0.1.100

log
)
// { _id: 'Chunk', values: [ 1, 2, 3, 4, 5 ] }

Sometimes, we may need to perform effectful state transformations during the unfolding operation. This is where Stream.unfoldEffect comes in handy. It allows us to work with effects while generating streams.

Here’s an example of creating an infinite stream of random 1 and -1 values using Stream.unfoldEffect:

import {
import Stream
Stream
,
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
,
import Option

@since2.0.0

@since2.0.0

Option
,
import Random
Random
} from "effect"
const
const stream: Stream.Stream<number, never, never>
stream
=
import Stream
Stream
.
const unfoldEffect: <number, number, never, never>(s: number, f: (s: number) => Effect.Effect<Option.Option<readonly [number, number]>, never, never>) => Stream.Stream<number, never, never>

Creates a stream by effectfully peeling off the "layers" of a value of type S.

@example

import { Effect, Option, Random, Stream } from "effect"
const stream = Stream.unfoldEffect(1, (n) =>
Random.nextBoolean.pipe(
Effect.map((b) => (b ? Option.some([n, -n]) : Option.some([n, n])))
))
// Effect.runPromise(Stream.runCollect(stream.pipe(Stream.take(5)))).then(console.log)
// { _id: 'Chunk', values: [ 1, -1, -1, -1, -1 ] }

@since2.0.0

unfoldEffect
(1, (
n: number
n
) =>
import Random
Random
.
const nextBoolean: Effect.Effect<boolean, never, never>

Returns the next boolean value from the pseudo-random number generator.

@since2.0.0

nextBoolean
.
Pipeable.pipe<Effect.Effect<boolean, never, never>, Effect.Effect<Option.Option<[number, number]>, never, never>>(this: Effect.Effect<...>, ab: (_: Effect.Effect<boolean, never, never>) => Effect.Effect<...>): Effect.Effect<...> (+21 overloads)
pipe
(
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
.
const map: <boolean, Option.Option<[number, number]>>(f: (a: boolean) => Option.Option<[number, number]>) => <E, R>(self: Effect.Effect<boolean, E, R>) => Effect.Effect<...> (+1 overload)

Transforms the value inside an effect by applying a function to it.

Syntax

const mappedEffect = pipe(myEffect, Effect.map(transformation))
// or
const mappedEffect = Effect.map(myEffect, transformation)
// or
const mappedEffect = myEffect.pipe(Effect.map(transformation))

Details

map takes a function and applies it to the value contained within an effect, creating a new effect with the transformed value.

It's important to note that effects are immutable, meaning that the original effect is not modified. Instead, a new effect is returned with the updated value.

@seemapError for a version that operates on the error channel.

@seemapBoth for a version that operates on both channels.

@seeflatMap or andThen for a version that can return a new effect.

@example

// Title: Adding a Service Charge
import { pipe, Effect } from "effect"
const addServiceCharge = (amount: number) => amount + 1
const fetchTransactionAmount = Effect.promise(() => Promise.resolve(100))
const finalAmount = pipe(
fetchTransactionAmount,
Effect.map(addServiceCharge)
)
Effect.runPromise(finalAmount).then(console.log)
// Output: 101

@since2.0.0

map
((
b: boolean
b
) => (
b: boolean
b
?
import Option

@since2.0.0

@since2.0.0

Option
.
const some: <[number, number]>(value: [number, number]) => Option.Option<[number, number]>

Creates a new Option that wraps the given value.

@paramvalue - The value to wrap.

@since2.0.0

some
([
n: number
n
, -
n: number
n
]) :
import Option

@since2.0.0

@since2.0.0

Option
.
const some: <[number, number]>(value: [number, number]) => Option.Option<[number, number]>

Creates a new Option that wraps the given value.

@paramvalue - The value to wrap.

@since2.0.0

some
([
n: number
n
,
n: number
n
])))
)
)
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
.
const runPromise: <Chunk<number>, never>(effect: Effect.Effect<Chunk<number>, never, never>, options?: {
readonly signal?: AbortSignal;
} | undefined) => Promise<Chunk<number>>

Executes an effect and returns the result as a Promise.

When to Use

Use runPromise when you need to execute an effect and work with the result using Promise syntax, typically for compatibility with other promise-based code.

If the effect succeeds, the promise will resolve with the result. If the effect fails, the promise will reject with an error.

@seerunPromiseExit for a version that returns an Exit type instead of rejecting.

@example

// Title: Running a Successful Effect as a Promise
import { Effect } from "effect"
Effect.runPromise(Effect.succeed(1)).then(console.log)
// Output: 1

@example

//Example: Handling a Failing Effect as a Rejected Promise import { Effect } from "effect"

Effect.runPromise(Effect.fail("my error")).catch(console.error) // Output: // (FiberFailure) Error: my error

@since2.0.0

runPromise
(
import Stream
Stream
.
const runCollect: <number, never, never>(self: Stream.Stream<number, never, never>) => Effect.Effect<Chunk<number>, never, never>

Runs the stream and collects all of its elements to a chunk.

@since2.0.0

runCollect
(
const stream: Stream.Stream<number, never, never>
stream
.
Pipeable.pipe<Stream.Stream<number, never, never>, Stream.Stream<number, never, never>>(this: Stream.Stream<...>, ab: (_: Stream.Stream<number, never, never>) => Stream.Stream<number, never, never>): Stream.Stream<...> (+21 overloads)
pipe
(
import Stream
Stream
.
const take: (n: number) => <A, E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<A, E, R> (+1 overload)

Takes the specified number of elements from this stream.

@example

import { Effect, Stream } from "effect"
const stream = Stream.take(Stream.iterate(0, (n) => n + 1), 5)
// Effect.runPromise(Stream.runCollect(stream)).then(console.log)
// { _id: 'Chunk', values: [ 0, 1, 2, 3, 4 ] }

@since2.0.0

take
(5)))).
Promise<Chunk<number>>.then<void, never>(onfulfilled?: ((value: Chunk<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.

@paramonfulfilled The callback to execute when the Promise is resolved.

@paramonrejected The callback to execute when the Promise is rejected.

@returnsA Promise for the completion of which ever callback is executed.

then
(
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 and process.stderr. 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 for more information.

Example using the global console:

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:

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

@seesource

console
.
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) (the arguments are all passed to util.format()).

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() for more information.

@sincev0.1.100

log
)
// Example Output: { _id: 'Chunk', values: [ 1, 1, 1, 1, -1 ] }

There are also similar operations like Stream.unfoldChunk and Stream.unfoldChunkEffect tailored for working with Chunk data types.

Stream.paginate is similar to Stream.unfold but allows emitting values one step further.

For example, the following stream emits 0, 1, 2, 3 elements:

import {
import Stream
Stream
,
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
,
import Option

@since2.0.0

@since2.0.0

Option
} from "effect"
const
const stream: Stream.Stream<number, never, never>
stream
=
import Stream
Stream
.
const paginate: <number, number>(s: number, f: (s: number) => readonly [number, Option.Option<number>]) => Stream.Stream<number, never, never>

Like Stream.unfold, but allows the emission of values to end one step further than the unfolding of the state. This is useful for embedding paginated APIs, hence the name.

@example

import { Effect, Option, Stream } from "effect"
const stream = Stream.paginate(0, (n) => [
n,
n < 3 ? Option.some(n + 1) : Option.none()
])
// Effect.runPromise(Stream.runCollect(stream)).then(console.log)
// { _id: 'Chunk', values: [ 0, 1, 2, 3 ] }

@since2.0.0

paginate
(0, (
n: number
n
) => [
n: number
n
,
n: number
n
< 3 ?
import Option

@since2.0.0

@since2.0.0

Option
.
const some: <number>(value: number) => Option.Option<number>

Creates a new Option that wraps the given value.

@paramvalue - The value to wrap.

@since2.0.0

some
(
n: number
n
+ 1) :
import Option

@since2.0.0

@since2.0.0

Option
.
const none: <number>() => Option.Option<number>

Creates a new Option that represents the absence of a value.

@since2.0.0

none
()
])
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
.
const runPromise: <Chunk<number>, never>(effect: Effect.Effect<Chunk<number>, never, never>, options?: {
readonly signal?: AbortSignal;
} | undefined) => Promise<Chunk<number>>

Executes an effect and returns the result as a Promise.

When to Use

Use runPromise when you need to execute an effect and work with the result using Promise syntax, typically for compatibility with other promise-based code.

If the effect succeeds, the promise will resolve with the result. If the effect fails, the promise will reject with an error.

@seerunPromiseExit for a version that returns an Exit type instead of rejecting.

@example

// Title: Running a Successful Effect as a Promise
import { Effect } from "effect"
Effect.runPromise(Effect.succeed(1)).then(console.log)
// Output: 1

@example

//Example: Handling a Failing Effect as a Rejected Promise import { Effect } from "effect"

Effect.runPromise(Effect.fail("my error")).catch(console.error) // Output: // (FiberFailure) Error: my error

@since2.0.0

runPromise
(
import Stream
Stream
.
const runCollect: <number, never, never>(self: Stream.Stream<number, never, never>) => Effect.Effect<Chunk<number>, never, never>

Runs the stream and collects all of its elements to a chunk.

@since2.0.0

runCollect
(
const stream: Stream.Stream<number, never, never>
stream
)).
Promise<Chunk<number>>.then<void, never>(onfulfilled?: ((value: Chunk<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.

@paramonfulfilled The callback to execute when the Promise is resolved.

@paramonrejected The callback to execute when the Promise is rejected.

@returnsA Promise for the completion of which ever callback is executed.

then
(
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 and process.stderr. 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 for more information.

Example using the global console:

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:

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

@seesource

console
.
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) (the arguments are all passed to util.format()).

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() for more information.

@sincev0.1.100

log
)
// { _id: 'Chunk', values: [ 0, 1, 2, 3 ] }

Here’s how it works:

  • We start with an initial value of 0.
  • The provided function takes the current value n and returns a tuple. The first element of the tuple is the value to emit (n), and the second element determines whether to continue (Option.some(n + 1)) or stop (Option.none()).

There are also similar operations like Stream.paginateChunk and Stream.paginateChunkEffect tailored for working with Chunk data types.

You might wonder about the difference between the unfold and paginate combinators and when to use one over the other. Let’s explore this by diving into an example.

Imagine we have a paginated API that provides a substantial amount of data in a paginated manner. When we make a request to this API, it returns a ResultPage object containing the results for the current page and a flag indicating whether it’s the last page or if there’s more data to retrieve on the next page. Here’s a simplified representation of our API:

import {
import Chunk
Chunk
,
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
} from "effect"
type
type RawData = string
RawData
= string
class
class PageResult
PageResult
{
constructor(
readonly
PageResult.results: Chunk.Chunk<string>
results
:
import Chunk
Chunk
.
interface Chunk<out A>

@since2.0.0

@since2.0.0

Chunk
<
type RawData = string
RawData
>,
readonly
PageResult.isLast: boolean
isLast
: boolean
) {}
}
const
const pageSize: 2
pageSize
= 2
const
const listPaginated: (pageNumber: number) => Effect.Effect<PageResult, Error>
listPaginated
= (
pageNumber: number
pageNumber
: number
):
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
.
interface Effect<out A, out E = never, out R = never>

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.

@since2.0.0

@since2.0.0

Effect
<
class PageResult
PageResult
,
interface Error
Error
> => {
return
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
.
const succeed: <PageResult>(value: PageResult) => Effect.Effect<PageResult, never, never>

Creates an Effect that always succeeds with a given value.

When to Use

Use this function when you need an effect that completes successfully with a specific value without any errors or external dependencies.

@seefail to create an effect that represents a failure.

@example

// Title: Creating a Successful Effect
import { Effect } from "effect"
// Creating an effect that represents a successful scenario
//
// ┌─── Effect<number, never, never>
// ▼
const success = Effect.succeed(42)

@since2.0.0

succeed
(
new
constructor PageResult(results: Chunk.Chunk<RawData>, isLast: boolean): PageResult
PageResult
(
import Chunk
Chunk
.
const map: <number, string>(self: Chunk.NonEmptyChunk<number>, f: (a: number, i: number) => string) => Chunk.NonEmptyChunk<string> (+2 overloads)

Transforms the elements of a chunk using the specified mapping function. If the input chunk is non-empty, the resulting chunk will also be non-empty.

@example

import { Chunk } from "effect"
assert.deepStrictEqual(
Chunk.map(Chunk.make(1, 2), (n) => n + 1),
Chunk.make(2, 3)
)

@since2.0.0

map
(
import Chunk
Chunk
.
const range: (start: number, end: number) => Chunk.NonEmptyChunk<number>

Create a non empty Chunk containing a range of integers, including both endpoints.

@since2.0.0

range
(1,
const pageSize: 2
pageSize
),
(
index: number
index
) => `Result ${
pageNumber: number
pageNumber
}-${
index: number
index
}`
),
pageNumber: number
pageNumber
=== 2 // Return 3 pages
)
)
}

Our goal is to convert this paginated API into a stream of RowData events. For our initial attempt, we might think that using the Stream.unfold operation is the way to go:

import {
import Chunk
Chunk
,
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
,
import Stream
Stream
,
import Option

@since2.0.0

@since2.0.0

Option
} from "effect"
24 collapsed lines
type
type RawData = string
RawData
= string
class
class PageResult
PageResult
{
constructor(
readonly
PageResult.results: Chunk.Chunk<string>
results
:
import Chunk
Chunk
.
interface Chunk<out A>

@since2.0.0

@since2.0.0

Chunk
<
type RawData = string
RawData
>,
readonly
PageResult.isLast: boolean
isLast
: boolean
) {}
}
const
const pageSize: 2
pageSize
= 2
const
const listPaginated: (pageNumber: number) => Effect.Effect<PageResult, Error>
listPaginated
= (
pageNumber: number
pageNumber
: number
):
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
.
interface Effect<out A, out E = never, out R = never>

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.

@since2.0.0

@since2.0.0

Effect
<
class PageResult
PageResult
,
interface Error
Error
> => {
return
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
.
const succeed: <PageResult>(value: PageResult) => Effect.Effect<PageResult, never, never>

Creates an Effect that always succeeds with a given value.

When to Use

Use this function when you need an effect that completes successfully with a specific value without any errors or external dependencies.

@seefail to create an effect that represents a failure.

@example

// Title: Creating a Successful Effect
import { Effect } from "effect"
// Creating an effect that represents a successful scenario
//
// ┌─── Effect<number, never, never>
// ▼
const success = Effect.succeed(42)

@since2.0.0

succeed
(
new
constructor PageResult(results: Chunk.Chunk<RawData>, isLast: boolean): PageResult
PageResult
(
import Chunk
Chunk
.
const map: <number, string>(self: Chunk.NonEmptyChunk<number>, f: (a: number, i: number) => string) => Chunk.NonEmptyChunk<string> (+2 overloads)

Transforms the elements of a chunk using the specified mapping function. If the input chunk is non-empty, the resulting chunk will also be non-empty.

@example

import { Chunk } from "effect"
assert.deepStrictEqual(
Chunk.map(Chunk.make(1, 2), (n) => n + 1),
Chunk.make(2, 3)
)

@since2.0.0

map
(
import Chunk
Chunk
.
const range: (start: number, end: number) => Chunk.NonEmptyChunk<number>

Create a non empty Chunk containing a range of integers, including both endpoints.

@since2.0.0

range
(1,
const pageSize: 2
pageSize
),
(
index: number
index
) => `Result ${
pageNumber: number
pageNumber
}-${
index: number
index
}`
),
pageNumber: number
pageNumber
=== 2 // Return 3 pages
)
)
}
const
const firstAttempt: Stream.Stream<string, Error, never>
firstAttempt
=
import Stream
Stream
.
const unfoldChunkEffect: <number, string, Error, never>(s: number, f: (s: number) => Effect.Effect<Option.Option<readonly [Chunk.Chunk<string>, number]>, Error, never>) => Stream.Stream<...>

Creates a stream by effectfully peeling off the "layers" of a value of type S.

@since2.0.0

unfoldChunkEffect
(0, (
pageNumber: number
pageNumber
) =>
const listPaginated: (pageNumber: number) => Effect.Effect<PageResult, Error>
listPaginated
(
pageNumber: number
pageNumber
).
Pipeable.pipe<Effect.Effect<PageResult, Error, never>, Effect.Effect<Option.None<readonly [Chunk.Chunk<string>, number]> | Option.Some<readonly [Chunk.Chunk<string>, number]>, Error, never>>(this: Effect.Effect<...>, ab: (_: Effect.Effect<...>) => Effect.Effect<...>): Effect.Effect<...> (+21 overloads)
pipe
(
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
.
const map: <PageResult, Option.None<readonly [Chunk.Chunk<string>, number]> | Option.Some<readonly [Chunk.Chunk<string>, number]>>(f: (a: PageResult) => Option.None<...> | Option.Some<...>) => <E, R>(self: Effect.Effect<...>) => Effect.Effect<...> (+1 overload)

Transforms the value inside an effect by applying a function to it.

Syntax

const mappedEffect = pipe(myEffect, Effect.map(transformation))
// or
const mappedEffect = Effect.map(myEffect, transformation)
// or
const mappedEffect = myEffect.pipe(Effect.map(transformation))

Details

map takes a function and applies it to the value contained within an effect, creating a new effect with the transformed value.

It's important to note that effects are immutable, meaning that the original effect is not modified. Instead, a new effect is returned with the updated value.

@seemapError for a version that operates on the error channel.

@seemapBoth for a version that operates on both channels.

@seeflatMap or andThen for a version that can return a new effect.

@example

// Title: Adding a Service Charge
import { pipe, Effect } from "effect"
const addServiceCharge = (amount: number) => amount + 1
const fetchTransactionAmount = Effect.promise(() => Promise.resolve(100))
const finalAmount = pipe(
fetchTransactionAmount,
Effect.map(addServiceCharge)
)
Effect.runPromise(finalAmount).then(console.log)
// Output: 101

@since2.0.0

map
((
page: PageResult
page
) => {
if (
page: PageResult
page
.
PageResult.isLast: boolean
isLast
) {
return
import Option

@since2.0.0

@since2.0.0

Option
.
const none: <never>() => Option.Option<never>

Creates a new Option that represents the absence of a value.

@since2.0.0

none
()
}
return
import Option

@since2.0.0

@since2.0.0

Option
.
const some: <readonly [Chunk.Chunk<string>, number]>(value: readonly [Chunk.Chunk<string>, number]) => Option.Option<readonly [Chunk.Chunk<string>, number]>

Creates a new Option that wraps the given value.

@paramvalue - The value to wrap.

@since2.0.0

some
([
page: PageResult
page
.
PageResult.results: Chunk.Chunk<string>
results
,
pageNumber: number
pageNumber
+ 1] as
type const = readonly [Chunk.Chunk<string>, number]
const
)
})
)
)
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
.
const runPromise: <Chunk.Chunk<string>, Error>(effect: Effect.Effect<Chunk.Chunk<string>, Error, never>, options?: {
readonly signal?: AbortSignal;
} | undefined) => Promise<...>

Executes an effect and returns the result as a Promise.

When to Use

Use runPromise when you need to execute an effect and work with the result using Promise syntax, typically for compatibility with other promise-based code.

If the effect succeeds, the promise will resolve with the result. If the effect fails, the promise will reject with an error.

@seerunPromiseExit for a version that returns an Exit type instead of rejecting.

@example

// Title: Running a Successful Effect as a Promise
import { Effect } from "effect"
Effect.runPromise(Effect.succeed(1)).then(console.log)
// Output: 1

@example

//Example: Handling a Failing Effect as a Rejected Promise import { Effect } from "effect"

Effect.runPromise(Effect.fail("my error")).catch(console.error) // Output: // (FiberFailure) Error: my error

@since2.0.0

runPromise
(
import Stream
Stream
.
const runCollect: <string, Error, never>(self: Stream.Stream<string, Error, never>) => Effect.Effect<Chunk.Chunk<string>, Error, never>

Runs the stream and collects all of its elements to a chunk.

@since2.0.0

runCollect
(
const firstAttempt: Stream.Stream<string, Error, never>
firstAttempt
)).
Promise<Chunk<string>>.then<void, never>(onfulfilled?: ((value: Chunk.Chunk<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.

@paramonfulfilled The callback to execute when the Promise is resolved.

@paramonrejected The callback to execute when the Promise is rejected.

@returnsA Promise for the completion of which ever callback is executed.

then
(
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 and process.stderr. 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 for more information.

Example using the global console:

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:

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

@seesource

console
.
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) (the arguments are all passed to util.format()).

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() for more information.

@sincev0.1.100

log
)
/*
Output:
{
_id: "Chunk",
values: [ "Result 0-1", "Result 0-2", "Result 1-1", "Result 1-2" ]
}
*/

However, this approach has a drawback, it doesn’t include the results from the last page. To work around this, we perform an extra API call to include those missing results:

import {
import Chunk
Chunk
,
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
,
import Stream
Stream
,
import Option

@since2.0.0

@since2.0.0

Option
} from "effect"
24 collapsed lines
type
type RawData = string
RawData
= string
class
class PageResult
PageResult
{
constructor(
readonly
PageResult.results: Chunk.Chunk<string>
results
:
import Chunk
Chunk
.
interface Chunk<out A>

@since2.0.0

@since2.0.0

Chunk
<
type RawData = string
RawData
>,
readonly
PageResult.isLast: boolean
isLast
: boolean
) {}
}
const
const pageSize: 2
pageSize
= 2
const
const listPaginated: (pageNumber: number) => Effect.Effect<PageResult, Error>
listPaginated
= (
pageNumber: number
pageNumber
: number
):
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
.
interface Effect<out A, out E = never, out R = never>

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.

@since2.0.0

@since2.0.0

Effect
<
class PageResult
PageResult
,
interface Error
Error
> => {
return
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
.
const succeed: <PageResult>(value: PageResult) => Effect.Effect<PageResult, never, never>

Creates an Effect that always succeeds with a given value.

When to Use

Use this function when you need an effect that completes successfully with a specific value without any errors or external dependencies.

@seefail to create an effect that represents a failure.

@example

// Title: Creating a Successful Effect
import { Effect } from "effect"
// Creating an effect that represents a successful scenario
//
// ┌─── Effect<number, never, never>
// ▼
const success = Effect.succeed(42)

@since2.0.0

succeed
(
new
constructor PageResult(results: Chunk.Chunk<RawData>, isLast: boolean): PageResult
PageResult
(
import Chunk
Chunk
.
const map: <number, string>(self: Chunk.NonEmptyChunk<number>, f: (a: number, i: number) => string) => Chunk.NonEmptyChunk<string> (+2 overloads)

Transforms the elements of a chunk using the specified mapping function. If the input chunk is non-empty, the resulting chunk will also be non-empty.

@example

import { Chunk } from "effect"
assert.deepStrictEqual(
Chunk.map(Chunk.make(1, 2), (n) => n + 1),
Chunk.make(2, 3)
)

@since2.0.0

map
(
import Chunk
Chunk
.
const range: (start: number, end: number) => Chunk.NonEmptyChunk<number>

Create a non empty Chunk containing a range of integers, including both endpoints.

@since2.0.0

range
(1,
const pageSize: 2
pageSize
),
(
index: number
index
) => `Result ${
pageNumber: number
pageNumber
}-${
index: number
index
}`
),
pageNumber: number
pageNumber
=== 2 // Return 3 pages
)
)
}
const
const secondAttempt: Stream.Stream<string, Error, never>
secondAttempt
=
import Stream
Stream
.
const unfoldChunkEffect: <Option.Option<number>, string, Error, never>(s: Option.Option<number>, f: (s: Option.Option<number>) => Effect.Effect<Option.Option<readonly [Chunk.Chunk<string>, Option.Option<number>]>, Error, never>) => Stream.Stream<...>

Creates a stream by effectfully peeling off the "layers" of a value of type S.

@since2.0.0

unfoldChunkEffect
(
import Option

@since2.0.0

@since2.0.0

Option
.
const some: <number>(value: number) => Option.Option<number>

Creates a new Option that wraps the given value.

@paramvalue - The value to wrap.

@since2.0.0

some
(0),
(
pageNumber: Option.Option<number>
pageNumber
) =>
import Option

@since2.0.0

@since2.0.0

Option
.
const match: <number, Effect.Effect<Option.Option<never>, never, never>, Effect.Effect<Option.Option<[Chunk.Chunk<string>, Option.None<number> | Option.Some<number>]>, Error, never>>(self: Option.Option<...>, options: {
...;
}) => Effect.Effect<...> | Effect.Effect<...> (+1 overload)

Matches the given Option and returns either the provided onNone value or the result of the provided onSome function when passed the Option's value.

@paramself - The Option to match

@paramonNone - The value to be returned if the Option is None

@paramonSome - The function to be called if the Option is Some, it will be passed the Option's value and its result will be returned

@example

import { pipe, Option } from "effect"
assert.deepStrictEqual(
pipe(Option.some(1), Option.match({ onNone: () => 'a none', onSome: (a) => `a some containing ${a}` })),
'a some containing 1'
)
assert.deepStrictEqual(
pipe(Option.none(), Option.match({ onNone: () => 'a none', onSome: (a) => `a some containing ${a}` })),
'a none'
)

@since2.0.0

match
(
pageNumber: Option.Option<number>
pageNumber
, {
// We already hit the last page
onNone: LazyArg<Effect.Effect<Option.Option<never>, never, never>>
onNone
: () =>
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
.
const succeed: <Option.Option<never>>(value: Option.Option<never>) => Effect.Effect<Option.Option<never>, never, never>

Creates an Effect that always succeeds with a given value.

When to Use

Use this function when you need an effect that completes successfully with a specific value without any errors or external dependencies.

@seefail to create an effect that represents a failure.

@example

// Title: Creating a Successful Effect
import { Effect } from "effect"
// Creating an effect that represents a successful scenario
//
// ┌─── Effect<number, never, never>
// ▼
const success = Effect.succeed(42)

@since2.0.0

succeed
(
import Option

@since2.0.0

@since2.0.0

Option
.
const none: <never>() => Option.Option<never>

Creates a new Option that represents the absence of a value.

@since2.0.0

none
()),
// We did not hit the last page yet
onSome: (a: number) => Effect.Effect<Option.Option<[Chunk.Chunk<string>, Option.None<number> | Option.Some<number>]>, Error, never>
onSome
: (
pageNumber: number
pageNumber
) =>
const listPaginated: (pageNumber: number) => Effect.Effect<PageResult, Error>
listPaginated
(
pageNumber: number
pageNumber
).
Pipeable.pipe<Effect.Effect<PageResult, Error, never>, Effect.Effect<Option.Option<[Chunk.Chunk<string>, Option.None<number> | Option.Some<number>]>, Error, never>>(this: Effect.Effect<...>, ab: (_: Effect.Effect<...>) => Effect.Effect<...>): Effect.Effect<...> (+21 overloads)
pipe
(
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
.
const map: <PageResult, Option.Option<[Chunk.Chunk<string>, Option.None<number> | Option.Some<number>]>>(f: (a: PageResult) => Option.Option<...>) => <E, R>(self: Effect.Effect<...>) => Effect.Effect<...> (+1 overload)

Transforms the value inside an effect by applying a function to it.

Syntax

const mappedEffect = pipe(myEffect, Effect.map(transformation))
// or
const mappedEffect = Effect.map(myEffect, transformation)
// or
const mappedEffect = myEffect.pipe(Effect.map(transformation))

Details

map takes a function and applies it to the value contained within an effect, creating a new effect with the transformed value.

It's important to note that effects are immutable, meaning that the original effect is not modified. Instead, a new effect is returned with the updated value.

@seemapError for a version that operates on the error channel.

@seemapBoth for a version that operates on both channels.

@seeflatMap or andThen for a version that can return a new effect.

@example

// Title: Adding a Service Charge
import { pipe, Effect } from "effect"
const addServiceCharge = (amount: number) => amount + 1
const fetchTransactionAmount = Effect.promise(() => Promise.resolve(100))
const finalAmount = pipe(
fetchTransactionAmount,
Effect.map(addServiceCharge)
)
Effect.runPromise(finalAmount).then(console.log)
// Output: 101

@since2.0.0

map
((
page: PageResult
page
) =>
import Option

@since2.0.0

@since2.0.0

Option
.
const some: <[Chunk.Chunk<string>, Option.None<number> | Option.Some<number>]>(value: [Chunk.Chunk<string>, Option.None<number> | Option.Some<number>]) => Option.Option<...>

Creates a new Option that wraps the given value.

@paramvalue - The value to wrap.

@since2.0.0

some
([
page: PageResult
page
.
PageResult.results: Chunk.Chunk<string>
results
,
page: PageResult
page
.
PageResult.isLast: boolean
isLast
?
import Option

@since2.0.0

@since2.0.0

Option
.
const none: <never>() => Option.Option<never>

Creates a new Option that represents the absence of a value.

@since2.0.0

none
() :
import Option

@since2.0.0

@since2.0.0

Option
.
const some: <number>(value: number) => Option.Option<number>

Creates a new Option that wraps the given value.

@paramvalue - The value to wrap.

@since2.0.0

some
(
pageNumber: number
pageNumber
+ 1)
])
)
)
})
)
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
.
const runPromise: <Chunk.Chunk<string>, Error>(effect: Effect.Effect<Chunk.Chunk<string>, Error, never>, options?: {
readonly signal?: AbortSignal;
} | undefined) => Promise<...>

Executes an effect and returns the result as a Promise.

When to Use

Use runPromise when you need to execute an effect and work with the result using Promise syntax, typically for compatibility with other promise-based code.

If the effect succeeds, the promise will resolve with the result. If the effect fails, the promise will reject with an error.

@seerunPromiseExit for a version that returns an Exit type instead of rejecting.

@example

// Title: Running a Successful Effect as a Promise
import { Effect } from "effect"
Effect.runPromise(Effect.succeed(1)).then(console.log)
// Output: 1

@example

//Example: Handling a Failing Effect as a Rejected Promise import { Effect } from "effect"

Effect.runPromise(Effect.fail("my error")).catch(console.error) // Output: // (FiberFailure) Error: my error

@since2.0.0

runPromise
(
import Stream
Stream
.
const runCollect: <string, Error, never>(self: Stream.Stream<string, Error, never>) => Effect.Effect<Chunk.Chunk<string>, Error, never>

Runs the stream and collects all of its elements to a chunk.

@since2.0.0

runCollect
(
const secondAttempt: Stream.Stream<string, Error, never>
secondAttempt
)).
Promise<Chunk<string>>.then<void, never>(onfulfilled?: ((value: Chunk.Chunk<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.

@paramonfulfilled The callback to execute when the Promise is resolved.

@paramonrejected The callback to execute when the Promise is rejected.

@returnsA Promise for the completion of which ever callback is executed.

then
(
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 and process.stderr. 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 for more information.

Example using the global console:

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:

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

@seesource

console
.
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) (the arguments are all passed to util.format()).

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() for more information.

@sincev0.1.100

log
)
/*
Output:
{
_id: 'Chunk',
values: [
'Result 0-1',
'Result 0-2',
'Result 1-1',
'Result 1-2',
'Result 2-1',
'Result 2-2'
]
}
*/

While this approach works, it’s clear that Stream.unfold isn’t the most friendly option for retrieving data from paginated APIs. It requires additional workarounds to include the results from the last page.

This is where Stream.paginate comes to the rescue. It provides a more ergonomic way to convert a paginated API into an Effect stream. Let’s rewrite our solution using Stream.paginate:

import {
import Chunk
Chunk
,
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
,
import Stream
Stream
,
import Option

@since2.0.0

@since2.0.0

Option
} from "effect"
24 collapsed lines
type
type RawData = string
RawData
= string
class
class PageResult
PageResult
{
constructor(
readonly
PageResult.results: Chunk.Chunk<string>
results
:
import Chunk
Chunk
.
interface Chunk<out A>

@since2.0.0

@since2.0.0

Chunk
<
type RawData = string
RawData
>,
readonly
PageResult.isLast: boolean
isLast
: boolean
) {}
}
const
const pageSize: 2
pageSize
= 2
const
const listPaginated: (pageNumber: number) => Effect.Effect<PageResult, Error>
listPaginated
= (
pageNumber: number
pageNumber
: number
):
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
.
interface Effect<out A, out E = never, out R = never>

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.

@since2.0.0

@since2.0.0

Effect
<
class PageResult
PageResult
,
interface Error
Error
> => {
return
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
.
const succeed: <PageResult>(value: PageResult) => Effect.Effect<PageResult, never, never>

Creates an Effect that always succeeds with a given value.

When to Use

Use this function when you need an effect that completes successfully with a specific value without any errors or external dependencies.

@seefail to create an effect that represents a failure.

@example

// Title: Creating a Successful Effect
import { Effect } from "effect"
// Creating an effect that represents a successful scenario
//
// ┌─── Effect<number, never, never>
// ▼
const success = Effect.succeed(42)

@since2.0.0

succeed
(
new
constructor PageResult(results: Chunk.Chunk<RawData>, isLast: boolean): PageResult
PageResult
(
import Chunk
Chunk
.
const map: <number, string>(self: Chunk.NonEmptyChunk<number>, f: (a: number, i: number) => string) => Chunk.NonEmptyChunk<string> (+2 overloads)

Transforms the elements of a chunk using the specified mapping function. If the input chunk is non-empty, the resulting chunk will also be non-empty.

@example

import { Chunk } from "effect"
assert.deepStrictEqual(
Chunk.map(Chunk.make(1, 2), (n) => n + 1),
Chunk.make(2, 3)
)

@since2.0.0

map
(
import Chunk
Chunk
.
const range: (start: number, end: number) => Chunk.NonEmptyChunk<number>

Create a non empty Chunk containing a range of integers, including both endpoints.

@since2.0.0

range
(1,
const pageSize: 2
pageSize
),
(
index: number
index
) => `Result ${
pageNumber: number
pageNumber
}-${
index: number
index
}`
),
pageNumber: number
pageNumber
=== 2 // Return 3 pages
)
)
}
const
const finalAttempt: Stream.Stream<string, Error, never>
finalAttempt
=
import Stream
Stream
.
const paginateChunkEffect: <number, string, Error, never>(s: number, f: (s: number) => Effect.Effect<readonly [Chunk.Chunk<string>, Option.Option<number>], Error, never>) => Stream.Stream<...>

Like Stream.unfoldChunkEffect, but allows the emission of values to end one step further than the unfolding of the state. This is useful for embedding paginated APIs, hence the name.

@since2.0.0

paginateChunkEffect
(0, (
pageNumber: number
pageNumber
) =>
const listPaginated: (pageNumber: number) => Effect.Effect<PageResult, Error>
listPaginated
(
pageNumber: number
pageNumber
).
Pipeable.pipe<Effect.Effect<PageResult, Error, never>, Effect.Effect<[Chunk.Chunk<string>, Option.Option<number>], Error, never>>(this: Effect.Effect<...>, ab: (_: Effect.Effect<...>) => Effect.Effect<...>): Effect.Effect<...> (+21 overloads)
pipe
(
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
.
const andThen: <PageResult, [Chunk.Chunk<string>, Option.Option<number>]>(f: (a: PageResult) => [Chunk.Chunk<string>, Option.Option<number>]) => <E, R>(self: Effect.Effect<...>) => Effect.Effect<...> (+3 overloads)

Chains two actions, where the second action can depend on the result of the first.

Syntax

const transformedEffect = pipe(myEffect, Effect.andThen(anotherEffect))
// or
const transformedEffect = Effect.andThen(myEffect, anotherEffect)
// or
const transformedEffect = myEffect.pipe(Effect.andThen(anotherEffect))

When to Use

Use andThen when you need to run multiple actions in sequence, with the second action depending on the result of the first. This is useful for combining effects or handling computations that must happen in order.

Details

The second action can be:

  • A constant value (similar to

as

)

  • A function returning a value (similar to

map

)

  • A Promise
  • A function returning a Promise
  • An Effect
  • A function returning an Effect (similar to

flatMap

)

Note: andThen works well with both Option and Either types, treating them as effects.

@example

// Title: Applying a Discount Based on Fetched Amount
import { pipe, Effect } from "effect"
// Function to apply a discount safely to a transaction amount
const applyDiscount = (
total: number,
discountRate: number
): Effect.Effect<number, Error> =>
discountRate === 0
? Effect.fail(new Error("Discount rate cannot be zero"))
: Effect.succeed(total - (total * discountRate) / 100)
// Simulated asynchronous task to fetch a transaction amount from database
const fetchTransactionAmount = Effect.promise(() => Promise.resolve(100))
// Using Effect.map and Effect.flatMap
const result1 = pipe(
fetchTransactionAmount,
Effect.map((amount) => amount * 2),
Effect.flatMap((amount) => applyDiscount(amount, 5))
)
Effect.runPromise(result1).then(console.log)
// Output: 190
// Using Effect.andThen
const result2 = pipe(
fetchTransactionAmount,
Effect.andThen((amount) => amount * 2),
Effect.andThen((amount) => applyDiscount(amount, 5))
)
Effect.runPromise(result2).then(console.log)
// Output: 190

@since2.0.0

andThen
((
page: PageResult
page
) => {
return [
page: PageResult
page
.
PageResult.results: Chunk.Chunk<string>
results
,
page: PageResult
page
.
PageResult.isLast: boolean
isLast
?
import Option

@since2.0.0

@since2.0.0

Option
.
const none: <number>() => Option.Option<number>

Creates a new Option that represents the absence of a value.

@since2.0.0

none
<number>() :
import Option

@since2.0.0

@since2.0.0

Option
.
const some: <number>(value: number) => Option.Option<number>

Creates a new Option that wraps the given value.

@paramvalue - The value to wrap.

@since2.0.0

some
(
pageNumber: number
pageNumber
+ 1)
]
})
)
)
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
.
const runPromise: <Chunk.Chunk<string>, Error>(effect: Effect.Effect<Chunk.Chunk<string>, Error, never>, options?: {
readonly signal?: AbortSignal;
} | undefined) => Promise<...>

Executes an effect and returns the result as a Promise.

When to Use

Use runPromise when you need to execute an effect and work with the result using Promise syntax, typically for compatibility with other promise-based code.

If the effect succeeds, the promise will resolve with the result. If the effect fails, the promise will reject with an error.

@seerunPromiseExit for a version that returns an Exit type instead of rejecting.

@example

// Title: Running a Successful Effect as a Promise
import { Effect } from "effect"
Effect.runPromise(Effect.succeed(1)).then(console.log)
// Output: 1

@example

//Example: Handling a Failing Effect as a Rejected Promise import { Effect } from "effect"

Effect.runPromise(Effect.fail("my error")).catch(console.error) // Output: // (FiberFailure) Error: my error

@since2.0.0

runPromise
(
import Stream
Stream
.
const runCollect: <string, Error, never>(self: Stream.Stream<string, Error, never>) => Effect.Effect<Chunk.Chunk<string>, Error, never>

Runs the stream and collects all of its elements to a chunk.

@since2.0.0

runCollect
(
const finalAttempt: Stream.Stream<string, Error, never>
finalAttempt
)).
Promise<Chunk<string>>.then<void, never>(onfulfilled?: ((value: Chunk.Chunk<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.

@paramonfulfilled The callback to execute when the Promise is resolved.

@paramonrejected The callback to execute when the Promise is rejected.

@returnsA Promise for the completion of which ever callback is executed.

then
(
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 and process.stderr. 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 for more information.

Example using the global console:

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:

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

@seesource

console
.
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) (the arguments are all passed to util.format()).

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() for more information.

@sincev0.1.100

log
)
/*
Output:
{
_id: 'Chunk',
values: [
'Result 0-1',
'Result 0-2',
'Result 1-1',
'Result 1-2',
'Result 2-1',
'Result 2-2'
]
}
*/

In Effect, there are two essential asynchronous messaging data types: Queue and PubSub. You can easily transform these data types into Streams by utilizing Stream.fromQueue and Stream.fromPubSub, respectively.

We can create a stream from a Schedule that does not require any further input. The stream will emit an element for each value output from the schedule, continuing for as long as the schedule continues:

import {
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
,
import Stream
Stream
,
import Schedule
Schedule
} from "effect"
// Emits values every 1 second for a total of 10 emissions
const
const schedule: Schedule.Schedule<number, unknown, never>
schedule
=
import Schedule
Schedule
.
const spaced: (duration: DurationInput) => Schedule.Schedule<number>

Returns a schedule that recurs continuously, each repetition spaced the specified duration from the last run.

@since2.0.0

spaced
("1 second").
Pipeable.pipe<Schedule.Schedule<number, unknown, never>, Schedule.Schedule<number, unknown, never>>(this: Schedule.Schedule<...>, ab: (_: Schedule.Schedule<number, unknown, never>) => Schedule.Schedule<number, unknown, never>): Schedule.Schedule<...> (+21 overloads)
pipe
(
import Schedule
Schedule
.
const compose: <number, unknown, never>(that: Schedule.Schedule<number, unknown, never>) => <In, R>(self: Schedule.Schedule<unknown, In, R>) => Schedule.Schedule<number, In, R> (+1 overload)

Returns the composition of this schedule and the specified schedule, by piping the output of this one into the input of the other. Effects described by this schedule will always be executed before the effects described by the second schedule.

@since2.0.0

compose
(
import Schedule
Schedule
.
const recurs: (n: number) => Schedule.Schedule<number>

A schedule spanning all time, which can be stepped only the specified number of times before it terminates.

@since2.0.0

recurs
(10))
)
const
const stream: Stream.Stream<number, never, never>
stream
=
import Stream
Stream
.
const fromSchedule: <number, never>(schedule: Schedule.Schedule<number, unknown, never>) => Stream.Stream<number, never, never>

Creates a stream from a Schedule that does not require any further input. The stream will emit an element for each value output from the schedule, continuing for as long as the schedule continues.

@example

import { Effect, Schedule, Stream } from "effect"
// Emits values every 1 second for a total of 5 emissions
const schedule = Schedule.spaced("1 second").pipe(
Schedule.compose(Schedule.recurs(5))
)
const stream = Stream.fromSchedule(schedule)
// Effect.runPromise(Stream.runCollect(stream)).then(console.log)
// { _id: 'Chunk', values: [ 0, 1, 2, 3, 4 ] }

@since2.0.0

fromSchedule
(
const schedule: Schedule.Schedule<number, unknown, never>
schedule
)
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
.
const runPromise: <Chunk<number>, never>(effect: Effect.Effect<Chunk<number>, never, never>, options?: {
readonly signal?: AbortSignal;
} | undefined) => Promise<Chunk<number>>

Executes an effect and returns the result as a Promise.

When to Use

Use runPromise when you need to execute an effect and work with the result using Promise syntax, typically for compatibility with other promise-based code.

If the effect succeeds, the promise will resolve with the result. If the effect fails, the promise will reject with an error.

@seerunPromiseExit for a version that returns an Exit type instead of rejecting.

@example

// Title: Running a Successful Effect as a Promise
import { Effect } from "effect"
Effect.runPromise(Effect.succeed(1)).then(console.log)
// Output: 1

@example

//Example: Handling a Failing Effect as a Rejected Promise import { Effect } from "effect"

Effect.runPromise(Effect.fail("my error")).catch(console.error) // Output: // (FiberFailure) Error: my error

@since2.0.0

runPromise
(
import Stream
Stream
.
const runCollect: <number, never, never>(self: Stream.Stream<number, never, never>) => Effect.Effect<Chunk<number>, never, never>

Runs the stream and collects all of its elements to a chunk.

@since2.0.0

runCollect
(
const stream: Stream.Stream<number, never, never>
stream
)).
Promise<Chunk<number>>.then<void, never>(onfulfilled?: ((value: Chunk<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.

@paramonfulfilled The callback to execute when the Promise is resolved.

@paramonrejected The callback to execute when the Promise is rejected.

@returnsA Promise for the completion of which ever callback is executed.

then
(
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 and process.stderr. 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 for more information.

Example using the global console:

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:

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

@seesource

console
.
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) (the arguments are all passed to util.format()).

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() for more information.

@sincev0.1.100

log
)
/*
Output:
{
_id: 'Chunk',
values: [
0, 1, 2, 3, 4,
5, 6, 7, 8, 9
]
}
*/