Skip to content

Getting Started with Micro

The Micro module is designed as a lighter alternative to the standard Effect module, tailored for situations where it is beneficial to reduce the bundle size.

This module is standalone and does not include more complex functionalities such as Layer, Ref, Queue, and Deferred. This feature set makes Micro especially suitable for libraries that wish to utilize Effect functionalities while keeping the bundle size to a minimum, particularly for those aiming to provide Promise-based APIs.

Micro also supports use cases where a client application uses Micro, and a server employs the full suite of Effect features, maintaining both compatibility and logical consistency across various application components.

Integrating Micro adds a minimal footprint to your bundle, starting at 5kb gzipped, which may increase depending on the features you use.

Before you start, make sure you have completed the following setup:

Install the effect library in your project. If it is not already installed, you can add it using npm with the following command:

Terminal window
npm install effect

Micro is a part of the Effect library and can be imported just like any other module:

import { Micro } from "effect"

You can also import it using a namespace import like this:

import { Micro } from "effect"

Here is the general form of a Micro:

┌─── Represents the success type
│ ┌─── Represents the error type
│ │ ┌─── Represents required dependencies
▼ ▼ ▼
Micro<Success, Error, Requirements>

which mirror those of the Effect type:

ParameterDescription
SuccessRepresents the type of value that an effect can succeed with when executed. If this type parameter is void, it means the effect produces no useful information, while if it is never, it means the effect runs forever (or until failure).
ErrorRepresents the expected errors that can occur when executing an effect. If this type parameter is never, it means the effect cannot fail, because there are no values of type never.
RequirementsRepresents the contextual data required by the effect to be executed. This data is stored in a collection named Context. If this type parameter is never, it means the effect has no requirements and the Context collection is empty.

The MicroExit type is used to represent the result of a Micro computation. It can either be successful, containing a value of type A, or it can fail, containing an error of type E wrapped in a MicroCause.

type MicroExit<A, E> = MicroExit.Success<A, E> | MicroExit.Failure<A, E>

The MicroCause type describes the different reasons why an effect may fail.

MicroCause comes in three forms:

type MicroCause<E> = Die | Fail<E> | Interrupt
VariantDescription
DieIndicates an unforeseen defect that wasn’t planned for in the system’s logic.
Fail<E>Covers anticipated errors that are recognized and typically handled within the application.
InterruptSignifies an operation that has been purposefully stopped.

This guide shows how to wrap a Promise-based API using the Micro library from Effect. We’ll create a simple example that interacts with a hypothetical weather forecasting API, using Micro to handle structured error handling and execution flow.

  1. Create a Promise-based API Function

    Start by defining a basic Promise-based function that simulates fetching weather data from an external service.

    // Simulate fetching weather data
    function
    function fetchWeather(city: string): Promise<string>
    fetchWeather
    (
    city: string
    city
    : string):
    interface Promise<T>

    Represents the completion of an asynchronous operation

    Promise
    <string> {
    return new
    var Promise: PromiseConstructor
    new <string>(executor: (resolve: (value: string | PromiseLike<string>) => void, reject: (reason?: any) => void) => void) => Promise<string>

    Creates a new Promise.

    @paramexecutor A callback used to initialize the promise. This callback is passed two arguments: a resolve callback used to resolve the promise with a value or the result of another promise, and a reject callback used to reject the promise with a provided reason or error.

    Promise
    ((
    resolve: (value: string | PromiseLike<string>) => void
    resolve
    ,
    reject: (reason?: any) => void
    reject
    ) => {
    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 (
    city: string
    city
    === "London") {
    resolve: (value: string | PromiseLike<string>) => void
    resolve
    ("Sunny")
    } else {
    reject: (reason?: any) => void
    reject
    (new
    var Error: ErrorConstructor
    new (message?: string) => Error
    Error
    ("Weather data not found for this location"))
    }
    }, 1_000)
    })
    }
  2. Wrap the Promise with Micro

    Now, wrap the fetchWeather function using Micro, converting the Promise to a Micro effect to manage both success and failure scenarios.

    import {
    import Micro
    Micro
    } from "effect"
    // Simulate fetching weather data
    11 collapsed lines
    function
    function fetchWeather(city: string): Promise<string>
    fetchWeather
    (
    city: string
    city
    : string):
    interface Promise<T>

    Represents the completion of an asynchronous operation

    Promise
    <string> {
    return new
    var Promise: PromiseConstructor
    new <string>(executor: (resolve: (value: string | PromiseLike<string>) => void, reject: (reason?: any) => void) => void) => Promise<string>

    Creates a new Promise.

    @paramexecutor A callback used to initialize the promise. This callback is passed two arguments: a resolve callback used to resolve the promise with a value or the result of another promise, and a reject callback used to reject the promise with a provided reason or error.

    Promise
    ((
    resolve: (value: string | PromiseLike<string>) => void
    resolve
    ,
    reject: (reason?: any) => void
    reject
    ) => {
    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 (
    city: string
    city
    === "London") {
    resolve: (value: string | PromiseLike<string>) => void
    resolve
    ("Sunny")
    } else {
    reject: (reason?: any) => void
    reject
    (new
    var Error: ErrorConstructor
    new (message?: string) => Error
    Error
    ("Weather data not found for this location"))
    }
    }, 1_000)
    })
    }
    function
    function getWeather(city: string): Micro.Micro<string, never, never>
    getWeather
    (
    city: string
    city
    : string) {
    return
    import Micro
    Micro
    .
    const promise: <string>(evaluate: (signal: AbortSignal) => PromiseLike<string>) => Micro.Micro<string, never, never>

    Wrap a Promise into a Micro effect.

    Any errors will result in a Die variant of the MicroCause type, where the error is not tracked at the type level.

    @since3.4.0

    promise
    (() =>
    function fetchWeather(city: string): Promise<string>
    fetchWeather
    (
    city: string
    city
    ))
    }

    Here, Micro.promise transforms the Promise returned by fetchWeather into a Micro<string, never, never> effect.

  3. Running the Micro Effect

    Once the function is wrapped, execute the Micro effect and handle the results.

    Example (Executing the Micro Effect)

    import {
    import Micro
    Micro
    } from "effect"
    // Simulate fetching weather data
    11 collapsed lines
    function
    function fetchWeather(city: string): Promise<string>
    fetchWeather
    (
    city: string
    city
    : string):
    interface Promise<T>

    Represents the completion of an asynchronous operation

    Promise
    <string> {
    return new
    var Promise: PromiseConstructor
    new <string>(executor: (resolve: (value: string | PromiseLike<string>) => void, reject: (reason?: any) => void) => void) => Promise<string>

    Creates a new Promise.

    @paramexecutor A callback used to initialize the promise. This callback is passed two arguments: a resolve callback used to resolve the promise with a value or the result of another promise, and a reject callback used to reject the promise with a provided reason or error.

    Promise
    ((
    resolve: (value: string | PromiseLike<string>) => void
    resolve
    ,
    reject: (reason?: any) => void
    reject
    ) => {
    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 (
    city: string
    city
    === "London") {
    resolve: (value: string | PromiseLike<string>) => void
    resolve
    ("Sunny")
    } else {
    reject: (reason?: any) => void
    reject
    (new
    var Error: ErrorConstructor
    new (message?: string) => Error
    Error
    ("Weather data not found for this location"))
    }
    }, 1_000)
    })
    }
    function
    function getWeather(city: string): Micro.Micro<string, never, never>
    getWeather
    (
    city: string
    city
    : string) {
    return
    import Micro
    Micro
    .
    const promise: <string>(evaluate: (signal: AbortSignal) => PromiseLike<string>) => Micro.Micro<string, never, never>

    Wrap a Promise into a Micro effect.

    Any errors will result in a Die variant of the MicroCause type, where the error is not tracked at the type level.

    @since3.4.0

    promise
    (() =>
    function fetchWeather(city: string): Promise<string>
    fetchWeather
    (
    city: string
    city
    ))
    }
    // ┌─── Micro<string, never, never>
    // ▼
    const
    const weatherEffect: Micro.Micro<string, never, never>
    weatherEffect
    =
    function getWeather(city: string): Micro.Micro<string, never, never>
    getWeather
    ("London")
    import Micro
    Micro
    .
    const runPromise: <string, never>(effect: Micro.Micro<string, never, never>, options?: {
    readonly signal?: AbortSignal | undefined;
    readonly scheduler?: Micro.MicroScheduler | undefined;
    } | undefined) => Promise<...>

    Execute the Micro effect and return a Promise that resolves with the successful value of the computation.

    @since3.4.0

    runPromise
    (
    const weatherEffect: Micro.Micro<string, never, never>
    weatherEffect
    )
    .
    Promise<string>.then<void, never>(onfulfilled?: ((value: string) => void | PromiseLike<void>) | null | undefined, onrejected?: ((reason: any) => PromiseLike<never>) | null | undefined): Promise<...>

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

    @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
    ((
    data: string
    data
    ) =>
    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
    (`The weather in London is: ${
    data: string
    data
    }`))
    .
    Promise<void>.catch<void>(onrejected?: ((reason: any) => void | PromiseLike<void>) | null | undefined): Promise<void>

    Attaches a callback for only the rejection of the Promise.

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

    @returnsA Promise for the completion of the callback.

    catch
    ((
    error: any
    error
    ) =>
    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.error(message?: any, ...optionalParams: any[]): void

    Prints to stderr 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 code = 5;
    console.error('error #%d', code);
    // Prints: error #5, to stderr
    console.error('error', code);
    // Prints: error 5, to stderr

    If formatting elements (e.g. %d) are not found in the first string then util.inspect() is called on each argument and the resulting string values are concatenated. See util.format() for more information.

    @sincev0.1.100

    error
    (`Failed to fetch weather data: ${
    error: any
    error
    .
    any
    message
    }`)
    )
    /*
    Output:
    The weather in London is: Sunny
    */

    In the example above, Micro.runPromise is used to execute the weatherEffect, converting it back into a Promise, which can be managed using familiar asynchronous handling methods.

    For more detailed information on the effect’s exit status, use Micro.runPromiseExit:

    Example (Inspecting Exit Status)

    import {
    import Micro
    Micro
    } from "effect"
    // Simulate fetching weather data
    11 collapsed lines
    function
    function fetchWeather(city: string): Promise<string>
    fetchWeather
    (
    city: string
    city
    : string):
    interface Promise<T>

    Represents the completion of an asynchronous operation

    Promise
    <string> {
    return new
    var Promise: PromiseConstructor
    new <string>(executor: (resolve: (value: string | PromiseLike<string>) => void, reject: (reason?: any) => void) => void) => Promise<string>

    Creates a new Promise.

    @paramexecutor A callback used to initialize the promise. This callback is passed two arguments: a resolve callback used to resolve the promise with a value or the result of another promise, and a reject callback used to reject the promise with a provided reason or error.

    Promise
    ((
    resolve: (value: string | PromiseLike<string>) => void
    resolve
    ,
    reject: (reason?: any) => void
    reject
    ) => {
    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 (
    city: string
    city
    === "London") {
    resolve: (value: string | PromiseLike<string>) => void
    resolve
    ("Sunny")
    } else {
    reject: (reason?: any) => void
    reject
    (new
    var Error: ErrorConstructor
    new (message?: string) => Error
    Error
    ("Weather data not found for this location"))
    }
    }, 1_000)
    })
    }
    function
    function getWeather(city: string): Micro.Micro<string, never, never>
    getWeather
    (
    city: string
    city
    : string) {
    return
    import Micro
    Micro
    .
    const promise: <string>(evaluate: (signal: AbortSignal) => PromiseLike<string>) => Micro.Micro<string, never, never>

    Wrap a Promise into a Micro effect.

    Any errors will result in a Die variant of the MicroCause type, where the error is not tracked at the type level.

    @since3.4.0

    promise
    (() =>
    function fetchWeather(city: string): Promise<string>
    fetchWeather
    (
    city: string
    city
    ))
    }
    // ┌─── Micro<string, never, never>
    // ▼
    const
    const weatherEffect: Micro.Micro<string, never, never>
    weatherEffect
    =
    function getWeather(city: string): Micro.Micro<string, never, never>
    getWeather
    ("London")
    import Micro
    Micro
    .
    const runPromiseExit: <string, never>(effect: Micro.Micro<string, never, never>, options?: {
    readonly signal?: AbortSignal | undefined;
    readonly scheduler?: Micro.MicroScheduler | undefined;
    } | undefined) => Promise<...>

    Execute the Micro effect and return a Promise that resolves with the MicroExit of the computation.

    @since3.4.6

    runPromiseExit
    (
    const weatherEffect: Micro.Micro<string, never, never>
    weatherEffect
    ).
    Promise<MicroExit<string, never>>.then<void, never>(onfulfilled?: ((value: Micro.MicroExit<string, 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
    (
    // ┌─── MicroExit<string, never>
    // ▼
    (
    exit: Micro.MicroExit<string, never>
    exit
    ) =>
    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
    (
    exit: Micro.MicroExit<string, never>
    exit
    )
    )
    /*
    Output:
    {
    "_id": "MicroExit",
    "_tag": "Success",
    "value": "Sunny"
    }
    */
  4. Adding Error Handling

    To further enhance the function, you might want to handle specific errors differently. Micro provides functions like Micro.tryPromise to handle anticipated errors gracefully.

    Example (Handling Specific Errors)

    import {
    import Micro
    Micro
    } from "effect"
    // Simulate fetching weather data
    11 collapsed lines
    function
    function fetchWeather(city: string): Promise<string>
    fetchWeather
    (
    city: string
    city
    : string):
    interface Promise<T>

    Represents the completion of an asynchronous operation

    Promise
    <string> {
    return new
    var Promise: PromiseConstructor
    new <string>(executor: (resolve: (value: string | PromiseLike<string>) => void, reject: (reason?: any) => void) => void) => Promise<string>

    Creates a new Promise.

    @paramexecutor A callback used to initialize the promise. This callback is passed two arguments: a resolve callback used to resolve the promise with a value or the result of another promise, and a reject callback used to reject the promise with a provided reason or error.

    Promise
    ((
    resolve: (value: string | PromiseLike<string>) => void
    resolve
    ,
    reject: (reason?: any) => void
    reject
    ) => {
    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 (
    city: string
    city
    === "London") {
    resolve: (value: string | PromiseLike<string>) => void
    resolve
    ("Sunny")
    } else {
    reject: (reason?: any) => void
    reject
    (new
    var Error: ErrorConstructor
    new (message?: string) => Error
    Error
    ("Weather data not found for this location"))
    }
    }, 1_000)
    })
    }
    class
    class WeatherError
    WeatherError
    {
    readonly
    WeatherError._tag: "WeatherError"
    _tag
    = "WeatherError"
    constructor(readonly
    WeatherError.message: string
    message
    : string) {}
    }
    function
    function getWeather(city: string): Micro.Micro<string, WeatherError, never>
    getWeather
    (
    city: string
    city
    : string) {
    return
    import Micro
    Micro
    .
    const tryPromise: <string, WeatherError>(options: {
    readonly try: (signal: AbortSignal) => PromiseLike<string>;
    readonly catch: (error: unknown) => WeatherError;
    }) => Micro.Micro<...>

    Wrap a Promise into a Micro effect. Any errors will be caught and converted into a specific error type.

    @example

    import { Micro } from "effect"
    Micro.tryPromise({
    try: () => Promise.resolve("success"),
    catch: (cause) => new Error("caught", { cause })
    })

    @since3.4.0

    tryPromise
    ({
    try: (signal: AbortSignal) => PromiseLike<string>
    try
    : () =>
    function fetchWeather(city: string): Promise<string>
    fetchWeather
    (
    city: string
    city
    ),
    // remap the error
    catch: (error: unknown) => WeatherError
    catch
    : (
    error: unknown
    error
    ) => new
    constructor WeatherError(message: string): WeatherError
    WeatherError
    (
    var String: StringConstructor
    (value?: any) => string

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

    String
    (
    error: unknown
    error
    ))
    })
    }
    // ┌─── Micro<string, WeatherError, never>
    // ▼
    const
    const weatherEffect: Micro.Micro<string, WeatherError, never>
    weatherEffect
    =
    function getWeather(city: string): Micro.Micro<string, WeatherError, never>
    getWeather
    ("Paris")
    import Micro
    Micro
    .
    const runPromise: <string, WeatherError>(effect: Micro.Micro<string, WeatherError, never>, options?: {
    readonly signal?: AbortSignal | undefined;
    readonly scheduler?: Micro.MicroScheduler | undefined;
    } | undefined) => Promise<...>

    Execute the Micro effect and return a Promise that resolves with the successful value of the computation.

    @since3.4.0

    runPromise
    (
    const weatherEffect: Micro.Micro<string, WeatherError, never>
    weatherEffect
    )
    .
    Promise<string>.then<void, never>(onfulfilled?: ((value: string) => void | PromiseLike<void>) | null | undefined, onrejected?: ((reason: any) => PromiseLike<never>) | null | undefined): Promise<...>

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

    @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
    ((
    data: string
    data
    ) =>
    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
    (`The weather in London is: ${
    data: string
    data
    }`))
    .
    Promise<void>.catch<void>(onrejected?: ((reason: any) => void | PromiseLike<void>) | null | undefined): Promise<void>

    Attaches a callback for only the rejection of the Promise.

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

    @returnsA Promise for the completion of the callback.

    catch
    ((
    error: any
    error
    ) =>
    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.error(message?: any, ...optionalParams: any[]): void

    Prints to stderr 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 code = 5;
    console.error('error #%d', code);
    // Prints: error #5, to stderr
    console.error('error', code);
    // Prints: error 5, to stderr

    If formatting elements (e.g. %d) are not found in the first string then util.inspect() is called on each argument and the resulting string values are concatenated. See util.format() for more information.

    @sincev0.1.100

    error
    (`Failed to fetch weather data: ${
    error: any
    error
    }`)
    )
    /*
    Output:
    Failed to fetch weather data: MicroCause.Fail: {"_tag":"WeatherError","message":"Error: Weather data not found for this location"}
    */

These errors, also referred to as failures, typed errors or recoverable errors, are errors that developers anticipate as part of the normal program execution. They serve a similar purpose to checked exceptions and play a role in defining the program’s domain and control flow.

Expected errors are tracked at the type level by the Micro data type in the “Error” channel:

┌─── Represents the success type
│ ┌─── Represents the error type
│ │ ┌─── Represents required dependencies
▼ ▼ ▼
Micro<Success, Error, Requirements>

The Micro.either function transforms an Micro<A, E, R> into an effect that encapsulates both potential failure and success within an Either data type:

Micro<A, E, R> -> Micro<Either<A, E>, never, R>

This means if you have an effect with the following type:

Micro<string, HttpError, never>

and you call Micro.either on it, the type becomes:

Micro<Either<string, HttpError>, never, never>

The resulting effect cannot fail because the potential failure is now represented within the Either’s Left type. The error type of the returned Micro is specified as never, confirming that the effect is structured to not fail.

By yielding an Either, we gain the ability to “pattern match” on this type to handle both failure and success cases within the generator function.

Example (Using Micro.either to Handle Errors)

import {
import Micro
Micro
,
import Either

@since2.0.0

@since2.0.0

Either
} from "effect"
class
class HttpError
HttpError
{
readonly
HttpError._tag: "HttpError"
_tag
= "HttpError"
}
class
class ValidationError
ValidationError
{
readonly
ValidationError._tag: "ValidationError"
_tag
= "ValidationError"
}
// ┌─── Micro<string, HttpError | ValidationError, never>
// ▼
const
const program: Micro.Micro<string, HttpError | ValidationError, never>
program
=
import Micro
Micro
.
const gen: <unknown, YieldWrap<Micro.Micro<never, HttpError, never>> | YieldWrap<Micro.Micro<never, ValidationError, never>>, string>(...args: [self: ...] | [body: ...]) => Micro.Micro<...>

@since3.4.0

gen
(function* () {
// Simulate http and validation errors
if (
var Math: Math

An intrinsic object that provides basic mathematics functionality and constants.

Math
.
Math.random(): number

Returns a pseudorandom number between 0 and 1.

random
() > 0.5) yield*
import Micro
Micro
.
const fail: <HttpError>(error: HttpError) => Micro.Micro<never, HttpError, never>

Creates a Micro effect that fails with the given error.

This results in a Fail variant of the MicroCause type, where the error is tracked at the type level.

@since3.4.0

fail
(new
constructor HttpError(): HttpError
HttpError
())
if (
var Math: Math

An intrinsic object that provides basic mathematics functionality and constants.

Math
.
Math.random(): number

Returns a pseudorandom number between 0 and 1.

random
() > 0.5) yield*
import Micro
Micro
.
const fail: <ValidationError>(error: ValidationError) => Micro.Micro<never, ValidationError, never>

Creates a Micro effect that fails with the given error.

This results in a Fail variant of the MicroCause type, where the error is tracked at the type level.

@since3.4.0

fail
(new
constructor ValidationError(): ValidationError
ValidationError
())
return "some result"
})
// ┌─── Micro<string, never, never>
// ▼
const
const recovered: Micro.Micro<string, never, never>
recovered
=
import Micro
Micro
.
const gen: <unknown, YieldWrap<Micro.Micro<Either.Either<string, HttpError | ValidationError>, never, never>>, string>(...args: [self: unknown, body: (this: unknown) => Generator<...>] | [body: ...]) => Micro.Micro<...>

@since3.4.0

gen
(function* () {
// ┌─── Either<string, HttpError | ValidationError>
// ▼
const
const failureOrSuccess: Either.Either<string, HttpError | ValidationError>
failureOrSuccess
= yield*
import Micro
Micro
.
const either: <string, HttpError | ValidationError, never>(self: Micro.Micro<string, HttpError | ValidationError, never>) => Micro.Micro<...>

Replace the success value of the given Micro effect with an Either, wrapping the success value in Right and wrapping any expected errors with a Left.

@since3.4.0

either
(
const program: Micro.Micro<string, HttpError | ValidationError, never>
program
)
return
import Either

@since2.0.0

@since2.0.0

Either
.
const match: <string, HttpError | ValidationError, string, string>(self: Either.Either<string, HttpError | ValidationError>, options: {
...;
}) => string (+1 overload)

Takes two functions and an Either value, if the value is a Left the inner value is applied to the onLeft function, if the value is a Rightthe inner value is applied to theonRight` function.

@example

import { pipe, Either } from "effect"
const onLeft = (strings: ReadonlyArray<string>): string => `strings: ${strings.join(', ')}`
const onRight = (value: number): string => `Ok: ${value}`
assert.deepStrictEqual(pipe(Either.right(1), Either.match({ onLeft, onRight })), 'Ok: 1')
assert.deepStrictEqual(
pipe(Either.left(['string 1', 'string 2']), Either.match({ onLeft, onRight })),
'strings: string 1, string 2'
)

@since2.0.0

match
(
const failureOrSuccess: Either.Either<string, HttpError | ValidationError>
failureOrSuccess
, {
// Failure case
onLeft: (left: HttpError | ValidationError) => string
onLeft
: (
error: HttpError | ValidationError
error
) => `Recovering from ${
error: HttpError | ValidationError
error
.
_tag: "HttpError" | "ValidationError"
_tag
}`,
// Success case
onRight: (right: string) => string
onRight
: (
value: string
value
) => `Result is: ${
value: string
value
}`
})
})
import Micro
Micro
.
const runPromiseExit: <string, never>(effect: Micro.Micro<string, never, never>, options?: {
readonly signal?: AbortSignal | undefined;
readonly scheduler?: Micro.MicroScheduler | undefined;
} | undefined) => Promise<...>

Execute the Micro effect and return a Promise that resolves with the MicroExit of the computation.

@since3.4.6

runPromiseExit
(
const recovered: Micro.Micro<string, never, never>
recovered
).
Promise<MicroExit<string, never>>.then<void, never>(onfulfilled?: ((value: Micro.MicroExit<string, 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
)
/*
Example Output:
{
"_id": "MicroExit",
"_tag": "Success",
"value": "Recovering from ValidationError"
}
*/

As you can see since all errors are handled, the error type of the resulting effect recovered is never:

const recovered: Micro<string, never, never>

The Micro.catchAll function allows you to catch any error that occurs in the program and provide a fallback.

Example (Catching All Errors with Micro.catchAll)

import {
import Micro
Micro
} from "effect"
class
class HttpError
HttpError
{
readonly
HttpError._tag: "HttpError"
_tag
= "HttpError"
}
class
class ValidationError
ValidationError
{
readonly
ValidationError._tag: "ValidationError"
_tag
= "ValidationError"
}
// ┌─── Micro<string, HttpError | ValidationError, never>
// ▼
const
const program: Micro.Micro<string, HttpError | ValidationError, never>
program
=
import Micro
Micro
.
const gen: <unknown, YieldWrap<Micro.Micro<never, HttpError, never>> | YieldWrap<Micro.Micro<never, ValidationError, never>>, string>(...args: [self: ...] | [body: ...]) => Micro.Micro<...>

@since3.4.0

gen
(function* () {
// Simulate http and validation errors
if (
var Math: Math

An intrinsic object that provides basic mathematics functionality and constants.

Math
.
Math.random(): number

Returns a pseudorandom number between 0 and 1.

random
() > 0.5) yield*
import Micro
Micro
.
const fail: <HttpError>(error: HttpError) => Micro.Micro<never, HttpError, never>

Creates a Micro effect that fails with the given error.

This results in a Fail variant of the MicroCause type, where the error is tracked at the type level.

@since3.4.0

fail
(new
constructor HttpError(): HttpError
HttpError
())
if (
var Math: Math

An intrinsic object that provides basic mathematics functionality and constants.

Math
.
Math.random(): number

Returns a pseudorandom number between 0 and 1.

random
() > 0.5) yield*
import Micro
Micro
.
const fail: <ValidationError>(error: ValidationError) => Micro.Micro<never, ValidationError, never>

Creates a Micro effect that fails with the given error.

This results in a Fail variant of the MicroCause type, where the error is tracked at the type level.

@since3.4.0

fail
(new
constructor ValidationError(): ValidationError
ValidationError
())
return "some result"
})
// ┌─── Micro<string, never, never>
// ▼
const
const recovered: Micro.Micro<string, never, never>
recovered
=
const program: Micro.Micro<string, HttpError | ValidationError, never>
program
.
Pipeable.pipe<Micro.Micro<string, HttpError | ValidationError, never>, Micro.Micro<string, never, never>>(this: Micro.Micro<...>, ab: (_: Micro.Micro<string, HttpError | ValidationError, never>) => Micro.Micro<...>): Micro.Micro<...> (+21 overloads)
pipe
(
import Micro
Micro
.
const catchAll: <HttpError | ValidationError, string, never, never>(f: (e: NoInfer<HttpError | ValidationError>) => Micro.Micro<string, never, never>) => <A, R>(self: Micro.Micro<...>) => Micro.Micro<...> (+1 overload)

Catch the error of the given Micro effect, allowing you to recover from it.

It only catches expected errors.

@since3.4.6

catchAll
((
error: NoInfer<HttpError | ValidationError>
error
) =>
import Micro
Micro
.
const succeed: <string>(value: string) => Micro.Micro<string, never, never>

Creates a Micro effect that will succeed with the specified constant value.

@since3.4.0

succeed
(`Recovering from ${
error: HttpError | ValidationError
error
.
_tag: "HttpError" | "ValidationError"
_tag
}`)
)
)
import Micro
Micro
.
const runPromiseExit: <string, never>(effect: Micro.Micro<string, never, never>, options?: {
readonly signal?: AbortSignal | undefined;
readonly scheduler?: Micro.MicroScheduler | undefined;
} | undefined) => Promise<...>

Execute the Micro effect and return a Promise that resolves with the MicroExit of the computation.

@since3.4.6

runPromiseExit
(
const recovered: Micro.Micro<string, never, never>
recovered
).
Promise<MicroExit<string, never>>.then<void, never>(onfulfilled?: ((value: Micro.MicroExit<string, 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
)
/*
Example Output:
{
"_id": "MicroExit",
"_tag": "Success",
"value": "Recovering from HttpError"
}
*/

We can observe that the type in the error channel of our program has changed to never:

const recovered: Micro<string, never, never>

indicating that all errors have been handled.

If your program’s errors are all tagged with a _tag field that acts as a discriminator you can use the Effect.catchTag function to catch and handle specific errors with precision.

Example (Handling Errors by Tag with Micro.catchTag)

import {
import Micro
Micro
} from "effect"
class
class HttpError
HttpError
{
readonly
HttpError._tag: "HttpError"
_tag
= "HttpError"
}
class
class ValidationError
ValidationError
{
readonly
ValidationError._tag: "ValidationError"
_tag
= "ValidationError"
}
// ┌─── Micro<string, HttpError | ValidationError, never>
// ▼
const
const program: Micro.Micro<string, HttpError | ValidationError, never>
program
=
import Micro
Micro
.
const gen: <unknown, YieldWrap<Micro.Micro<never, HttpError, never>> | YieldWrap<Micro.Micro<never, ValidationError, never>>, string>(...args: [self: ...] | [body: ...]) => Micro.Micro<...>

@since3.4.0

gen
(function* () {
// Simulate http and validation errors
if (
var Math: Math

An intrinsic object that provides basic mathematics functionality and constants.

Math
.
Math.random(): number

Returns a pseudorandom number between 0 and 1.

random
() > 0.5) yield*
import Micro
Micro
.
const fail: <HttpError>(error: HttpError) => Micro.Micro<never, HttpError, never>

Creates a Micro effect that fails with the given error.

This results in a Fail variant of the MicroCause type, where the error is tracked at the type level.

@since3.4.0

fail
(new
constructor HttpError(): HttpError
HttpError
())
if (
var Math: Math

An intrinsic object that provides basic mathematics functionality and constants.

Math
.
Math.random(): number

Returns a pseudorandom number between 0 and 1.

random
() > 0.5) yield*
import Micro
Micro
.
const fail: <ValidationError>(error: ValidationError) => Micro.Micro<never, ValidationError, never>

Creates a Micro effect that fails with the given error.

This results in a Fail variant of the MicroCause type, where the error is tracked at the type level.

@since3.4.0

fail
(new
constructor ValidationError(): ValidationError
ValidationError
())
return "Success"
})
// ┌─── Micro<string, ValidationError, never>
// ▼
const
const recovered: Micro.Micro<string, ValidationError, never>
recovered
=
const program: Micro.Micro<string, HttpError | ValidationError, never>
program
.
Pipeable.pipe<Micro.Micro<string, HttpError | ValidationError, never>, Micro.Micro<string, ValidationError, never>>(this: Micro.Micro<...>, ab: (_: Micro.Micro<...>) => Micro.Micro<...>): Micro.Micro<...> (+21 overloads)
pipe
(
import Micro
Micro
.
const catchTag: <"HttpError", HttpError | ValidationError, string, never, never>(k: "HttpError", f: (e: HttpError) => Micro.Micro<string, never, never>) => <A, R>(self: Micro.Micro<...>) => Micro.Micro<...> (+1 overload)

Recovers from the specified tagged error.

@since3.4.0

catchTag
("HttpError", (
_HttpError: HttpError
_HttpError
) =>
import Micro
Micro
.
const succeed: <string>(value: string) => Micro.Micro<string, never, never>

Creates a Micro effect that will succeed with the specified constant value.

@since3.4.0

succeed
("Recovering from HttpError")
)
)
import Micro
Micro
.
const runPromiseExit: <string, ValidationError>(effect: Micro.Micro<string, ValidationError, never>, options?: {
readonly signal?: AbortSignal | undefined;
readonly scheduler?: Micro.MicroScheduler | undefined;
} | undefined) => Promise<...>

Execute the Micro effect and return a Promise that resolves with the MicroExit of the computation.

@since3.4.6

runPromiseExit
(
const recovered: Micro.Micro<string, ValidationError, never>
recovered
).
Promise<MicroExit<string, ValidationError>>.then<void, never>(onfulfilled?: ((value: Micro.MicroExit<string, ValidationError>) => void | PromiseLike<void>) | null | undefined, onrejected?: ((reason: any) => PromiseLike<...>) | 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": "MicroExit",
"_tag": "Success",
"value": "Recovering from HttpError"
}
*/

In the example above, the Micro.catchTag function allows us to handle HttpError specifically. If a HttpError occurs during the execution of the program, the provided error handler function will be invoked, and the program will proceed with the recovery logic specified within the handler.

We can observe that the type in the error channel of our program has changed to only show ValidationError:

const recovered: Micro<string, ValidationError, never>

indicating that HttpError has been handled.

Unexpected errors, also referred to as defects, untyped errors, or unrecoverable errors, are errors that developers do not anticipate occurring during normal program execution. Unlike expected errors, which are considered part of a program’s domain and control flow, unexpected errors resemble unchecked exceptions and lie outside the expected behavior of the program.

Since these errors are not expected, Effect does not track them at the type level. However, the Effect runtime does keep track of these errors and provides several methods to aid in recovering from unexpected errors.

The Micro.die function returns an effect that throws a specified error. This function is useful for terminating a program when a defect, a critical and unexpected error, is detected in the code.

Example (Terminating on Division by Zero with Effect.die)

import {
import Micro
Micro
} from "effect"
const
const divide: (a: number, b: number) => Micro.Micro<number>
divide
= (
a: number
a
: number,
b: number
b
: number):
import Micro
Micro
.
interface Micro<out A, out E = never, out R = never>

A lightweight alternative to the Effect data type, with a subset of the functionality.

@since3.4.0

@since3.4.0

Micro
<number> =>
b: number
b
=== 0
?
import Micro
Micro
.
const die: (defect: unknown) => Micro.Micro<never>

Creates a Micro effect that will die with the specified error.

This results in a Die variant of the MicroCause type, where the error is not tracked at the type level.

@since3.4.0

die
(new
var Error: ErrorConstructor
new (message?: string) => Error
Error
("Cannot divide by zero"))
:
import Micro
Micro
.
const succeed: <number>(value: number) => Micro.Micro<number, never, never>

Creates a Micro effect that will succeed with the specified constant value.

@since3.4.0

succeed
(
a: number
a
/
b: number
b
)
import Micro
Micro
.
const runPromise: <number, never>(effect: Micro.Micro<number, never, never>, options?: {
readonly signal?: AbortSignal | undefined;
readonly scheduler?: Micro.MicroScheduler | undefined;
} | undefined) => Promise<...>

Execute the Micro effect and return a Promise that resolves with the successful value of the computation.

@since3.4.0

runPromise
(
const divide: (a: number, b: number) => Micro.Micro<number>
divide
(1, 0))
/*
throws:
Die [(MicroCause.Die) Error]: Cannot divide by zero
...stack trace...
*/

The Micro.orDie function converts an effect’s failure into a termination of the program, removing the error from the type of the effect. It is useful when you encounter failures that you do not intend to handle or recover from.

Example (Converting Failure to Defect with Micro.orDie)

import {
import Micro
Micro
} from "effect"
const
const divide: (a: number, b: number) => Micro.Micro<number, Error>
divide
= (
a: number
a
: number,
b: number
b
: number):
import Micro
Micro
.
interface Micro<out A, out E = never, out R = never>

A lightweight alternative to the Effect data type, with a subset of the functionality.

@since3.4.0

@since3.4.0

Micro
<number,
interface Error
Error
> =>
b: number
b
=== 0
?
import Micro
Micro
.
const fail: <Error>(error: Error) => Micro.Micro<never, Error, never>

Creates a Micro effect that fails with the given error.

This results in a Fail variant of the MicroCause type, where the error is tracked at the type level.

@since3.4.0

fail
(new
var Error: ErrorConstructor
new (message?: string) => Error
Error
("Cannot divide by zero"))
:
import Micro
Micro
.
const succeed: <number>(value: number) => Micro.Micro<number, never, never>

Creates a Micro effect that will succeed with the specified constant value.

@since3.4.0

succeed
(
a: number
a
/
b: number
b
)
// ┌─── Micro<number, never, never>
// ▼
const
const program: Micro.Micro<number, never, never>
program
=
import Micro
Micro
.
const orDie: <number, Error, never>(self: Micro.Micro<number, Error, never>) => Micro.Micro<number, never, never>

Elevate any expected errors of the given Micro effect to unexpected errors, resulting in an error type of never.

@since3.4.0

orDie
(
const divide: (a: number, b: number) => Micro.Micro<number, Error>
divide
(1, 0))
import Micro
Micro
.
const runPromise: <number, never>(effect: Micro.Micro<number, never, never>, options?: {
readonly signal?: AbortSignal | undefined;
readonly scheduler?: Micro.MicroScheduler | undefined;
} | undefined) => Promise<...>

Execute the Micro effect and return a Promise that resolves with the successful value of the computation.

@since3.4.0

runPromise
(
const program: Micro.Micro<number, never, never>
program
)
/*
throws:
Die [(MicroCause.Die) Error]: Cannot divide by zero
...stack trace...
*/

The Micro.catchAllDefect function allows you to recover from all defects using a provided function.

Example (Handling All Defects with Micro.catchAllDefect)

import {
import Micro
Micro
} from "effect"
// Helper function to log a message
const
const log: (message: string) => Micro.Micro<void, never, never>
log
= (
message: string
message
: string) =>
import Micro
Micro
.
const sync: <void>(evaluate: LazyArg<void>) => Micro.Micro<void, never, never>

Creates a Micro effect that succeeds with a lazily evaluated value.

If the evaluation of the value throws an error, the effect will fail with a Die variant of the MicroCause type.

@since3.4.0

sync
(() =>
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
(
message: string
message
))
// Simulating a runtime error
const
const task: Micro.Micro<never, never, never>
task
=
import Micro
Micro
.
const die: (defect: unknown) => Micro.Micro<never>

Creates a Micro effect that will die with the specified error.

This results in a Die variant of the MicroCause type, where the error is not tracked at the type level.

@since3.4.0

die
("Boom!")
const
const program: Micro.Micro<void, never, never>
program
=
import Micro
Micro
.
const catchAllDefect: <never, never, never, void, never, never>(self: Micro.Micro<never, never, never>, f: (defect: unknown) => Micro.Micro<void, never, never>) => Micro.Micro<void, never, never> (+1 overload)

Catch any unexpected errors of the given Micro effect, allowing you to recover from them.

@since3.4.6

catchAllDefect
(
const task: Micro.Micro<never, never, never>
task
, (
defect: unknown
defect
) =>
const log: (message: string) => Micro.Micro<void, never, never>
log
(`Unknown defect caught: ${
defect: unknown
defect
}`)
)
// We get a Right because we caught all defects
import Micro
Micro
.
const runPromiseExit: <void, never>(effect: Micro.Micro<void, never, never>, options?: {
readonly signal?: AbortSignal | undefined;
readonly scheduler?: Micro.MicroScheduler | undefined;
} | undefined) => Promise<...>

Execute the Micro effect and return a Promise that resolves with the MicroExit of the computation.

@since3.4.6

runPromiseExit
(
const program: Micro.Micro<void, never, never>
program
).
Promise<MicroExit<void, never>>.then<void, never>(onfulfilled?: ((value: Micro.MicroExit<void, never>) => void | PromiseLike<void>) | null | undefined, onrejected?: ((reason: any) => PromiseLike<never>) | null | undefined): Promise<...>

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

@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
((
exit: Micro.MicroExit<void, never>
exit
) =>
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
(
exit: Micro.MicroExit<void, never>
exit
))
/*
Output:
Unknown defect caught: Boom!
{
"_id": "MicroExit",
"_tag": "Success"
}
*/

It’s important to understand that Micro.catchAllDefect can only handle defects, not expected errors (such as those caused by Micro.fail) or interruptions in execution (such as when using Micro.interrupt).

A defect refers to an error that cannot be anticipated in advance, and there is no reliable way to respond to it. As a general rule, it’s recommended to let defects crash the application, as they often indicate serious issues that need to be addressed.

However, in some specific cases, such as when dealing with dynamically loaded plugins, a controlled recovery approach might be necessary. For example, if our application supports runtime loading of plugins and a defect occurs within a plugin, we may choose to log the defect and then reload only the affected plugin instead of crashing the entire application. This allows for a more resilient and uninterrupted operation of the application.

The Effect.orElseSucceed function will replace the original failure with a success value, ensuring the effect cannot fail:

Example (Replacing Failure with Success using Micro.orElseSucceed)

import {
import Micro
Micro
} from "effect"
const
const validate: (age: number) => Micro.Micro<number, string>
validate
= (
age: number
age
: number):
import Micro
Micro
.
interface Micro<out A, out E = never, out R = never>

A lightweight alternative to the Effect data type, with a subset of the functionality.

@since3.4.0

@since3.4.0

Micro
<number, string> => {
if (
age: number
age
< 0) {
return
import Micro
Micro
.
const fail: <string>(error: string) => Micro.Micro<never, string, never>

Creates a Micro effect that fails with the given error.

This results in a Fail variant of the MicroCause type, where the error is tracked at the type level.

@since3.4.0

fail
("NegativeAgeError")
} else if (
age: number
age
< 18) {
return
import Micro
Micro
.
const fail: <string>(error: string) => Micro.Micro<never, string, never>

Creates a Micro effect that fails with the given error.

This results in a Fail variant of the MicroCause type, where the error is tracked at the type level.

@since3.4.0

fail
("IllegalAgeError")
} else {
return
import Micro
Micro
.
const succeed: <number>(value: number) => Micro.Micro<number, never, never>

Creates a Micro effect that will succeed with the specified constant value.

@since3.4.0

succeed
(
age: number
age
)
}
}
const
const program: Micro.Micro<number, never, never>
program
=
import Micro
Micro
.
const orElseSucceed: <number, string, never, number>(self: Micro.Micro<number, string, never>, f: LazyArg<number>) => Micro.Micro<number, never, never> (+1 overload)

Recover from all errors by succeeding with the given value.

@since3.4.0

orElseSucceed
(
const validate: (age: number) => Micro.Micro<number, string>
validate
(-1), () => 18)
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
(
import Micro
Micro
.
const runSyncExit: <number, never>(effect: Micro.Micro<number, never, never>) => Micro.MicroExit<number, never>

Attempt to execute the Micro effect synchronously and return the MicroExit.

If any asynchronous effects are encountered, the function will return a CauseDie containing the MicroFiber.

@since3.4.6

runSyncExit
(
const program: Micro.Micro<number, never, never>
program
))
/*
Output:
{
"_id": "MicroExit",
"_tag": "Success",
"value": 18
}
*/

The Micro.match function lets you handle both success and failure cases without performing side effects. You provide a handler for each case.

Example (Handling Both Success and Failure Cases)

import {
import Micro
Micro
} from "effect"
const
const success: Micro.Micro<number, Error, never>
success
:
import Micro
Micro
.
interface Micro<out A, out E = never, out R = never>

A lightweight alternative to the Effect data type, with a subset of the functionality.

@since3.4.0

@since3.4.0

Micro
<number,
interface Error
Error
> =
import Micro
Micro
.
const succeed: <number>(value: number) => Micro.Micro<number, never, never>

Creates a Micro effect that will succeed with the specified constant value.

@since3.4.0

succeed
(42)
const
const program1: Micro.Micro<string, never, never>
program1
=
import Micro
Micro
.
const match: <number, Error, never, string, string>(self: Micro.Micro<number, Error, never>, options: {
readonly onFailure: (error: Error) => string;
readonly onSuccess: (value: number) => string;
}) => Micro.Micro<...> (+1 overload)

@since3.4.0

match
(
const success: Micro.Micro<number, Error, never>
success
, {
onFailure: (error: Error) => string
onFailure
: (
error: Error
error
) => `failure: ${
error: Error
error
.
Error.message: string
message
}`,
onSuccess: (value: number) => string
onSuccess
: (
value: number
value
) => `success: ${
value: number
value
}`
})
// Run and log the result of the successful effect
import Micro
Micro
.
const runPromise: <string, never>(effect: Micro.Micro<string, never, never>, options?: {
readonly signal?: AbortSignal | undefined;
readonly scheduler?: Micro.MicroScheduler | undefined;
} | undefined) => Promise<...>

Execute the Micro effect and return a Promise that resolves with the successful value of the computation.

@since3.4.0

runPromise
(
const program1: Micro.Micro<string, never, never>
program1
).
Promise<string>.then<void, never>(onfulfilled?: ((value: string) => void | PromiseLike<void>) | null | undefined, onrejected?: ((reason: any) => PromiseLike<never>) | null | undefined): Promise<...>

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

@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: "success: 42"
const
const failure: Micro.Micro<number, Error, never>
failure
:
import Micro
Micro
.
interface Micro<out A, out E = never, out R = never>

A lightweight alternative to the Effect data type, with a subset of the functionality.

@since3.4.0

@since3.4.0

Micro
<number,
interface Error
Error
> =
import Micro
Micro
.
const fail: <Error>(error: Error) => Micro.Micro<never, Error, never>

Creates a Micro effect that fails with the given error.

This results in a Fail variant of the MicroCause type, where the error is tracked at the type level.

@since3.4.0

fail
(
new
var Error: ErrorConstructor
new (message?: string) => Error
Error
("Uh oh!")
)
const
const program2: Micro.Micro<string, never, never>
program2
=
import Micro
Micro
.
const match: <number, Error, never, string, string>(self: Micro.Micro<number, Error, never>, options: {
readonly onFailure: (error: Error) => string;
readonly onSuccess: (value: number) => string;
}) => Micro.Micro<...> (+1 overload)

@since3.4.0

match
(
const failure: Micro.Micro<number, Error, never>
failure
, {
onFailure: (error: Error) => string
onFailure
: (
error: Error
error
) => `failure: ${
error: Error
error
.
Error.message: string
message
}`,
onSuccess: (value: number) => string
onSuccess
: (
value: number
value
) => `success: ${
value: number
value
}`
})
// Run and log the result of the failed effect
import Micro
Micro
.
const runPromise: <string, never>(effect: Micro.Micro<string, never, never>, options?: {
readonly signal?: AbortSignal | undefined;
readonly scheduler?: Micro.MicroScheduler | undefined;
} | undefined) => Promise<...>

Execute the Micro effect and return a Promise that resolves with the successful value of the computation.

@since3.4.0

runPromise
(
const program2: Micro.Micro<string, never, never>
program2
).
Promise<string>.then<void, never>(onfulfilled?: ((value: string) => void | PromiseLike<void>) | null | undefined, onrejected?: ((reason: any) => PromiseLike<never>) | null | undefined): Promise<...>

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

@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: "failure: Uh oh!"

The Micro.matchEffect function, similar to Micro.match, allows you to handle both success and failure cases, but it also enables you to perform additional side effects within those handlers.

Example (Handling Success and Failure with Side Effects)

import {
import Micro
Micro
} from "effect"
// Helper function to log a message
const
const log: (message: string) => Micro.Micro<void, never, never>
log
= (
message: string
message
: string) =>
import Micro
Micro
.
const sync: <void>(evaluate: LazyArg<void>) => Micro.Micro<void, never, never>

Creates a Micro effect that succeeds with a lazily evaluated value.

If the evaluation of the value throws an error, the effect will fail with a Die variant of the MicroCause type.

@since3.4.0

sync
(() =>
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
(
message: string
message
))
const
const success: Micro.Micro<number, Error, never>
success
:
import Micro
Micro
.
interface Micro<out A, out E = never, out R = never>

A lightweight alternative to the Effect data type, with a subset of the functionality.

@since3.4.0

@since3.4.0

Micro
<number,
interface Error
Error
> =
import Micro
Micro
.
const succeed: <number>(value: number) => Micro.Micro<number, never, never>

Creates a Micro effect that will succeed with the specified constant value.

@since3.4.0

succeed
(42)
const
const failure: Micro.Micro<number, Error, never>
failure
:
import Micro
Micro
.
interface Micro<out A, out E = never, out R = never>

A lightweight alternative to the Effect data type, with a subset of the functionality.

@since3.4.0

@since3.4.0

Micro
<number,
interface Error
Error
> =
import Micro
Micro
.
const fail: <Error>(error: Error) => Micro.Micro<never, Error, never>

Creates a Micro effect that fails with the given error.

This results in a Fail variant of the MicroCause type, where the error is tracked at the type level.

@since3.4.0

fail
(
new
var Error: ErrorConstructor
new (message?: string) => Error
Error
("Uh oh!")
)
const
const program1: Micro.Micro<string, never, never>
program1
=
import Micro
Micro
.
const matchEffect: <number, Error, never, string, never, never, string, never, never>(self: Micro.Micro<number, Error, never>, options: {
readonly onFailure: (e: Error) => Micro.Micro<string, never, never>;
readonly onSuccess: (a: number) => Micro.Micro<...>;
}) => Micro.Micro<...> (+1 overload)

@since3.4.6

matchEffect
(
const success: Micro.Micro<number, Error, never>
success
, {
onFailure: (e: Error) => Micro.Micro<string, never, never>
onFailure
: (
error: Error
error
) =>
import Micro
Micro
.
const succeed: <string>(value: string) => Micro.Micro<string, never, never>

Creates a Micro effect that will succeed with the specified constant value.

@since3.4.0

succeed
(`failure: ${
error: Error
error
.
Error.message: string
message
}`).
Pipeable.pipe<Micro.Micro<string, never, never>, Micro.Micro<string, never, never>>(this: Micro.Micro<...>, ab: (_: Micro.Micro<string, never, never>) => Micro.Micro<string, never, never>): Micro.Micro<...> (+21 overloads)
pipe
(
import Micro
Micro
.
const tap: <string, Micro.Micro<void, never, never>>(f: (a: string) => Micro.Micro<void, never, never>) => <E, R>(self: Micro.Micro<string, E, R>) => Micro.Micro<string, E, R> (+3 overloads)

Execute a side effect from the success value of the Micro effect.

It is similar to the andThen api, but the success value is ignored.

@since3.4.0

tap
(
const log: (message: string) => Micro.Micro<void, never, never>
log
)),
onSuccess: (a: number) => Micro.Micro<string, never, never>
onSuccess
: (
value: number
value
) =>
import Micro
Micro
.
const succeed: <string>(value: string) => Micro.Micro<string, never, never>

Creates a Micro effect that will succeed with the specified constant value.

@since3.4.0

succeed
(`success: ${
value: number
value
}`).
Pipeable.pipe<Micro.Micro<string, never, never>, Micro.Micro<string, never, never>>(this: Micro.Micro<...>, ab: (_: Micro.Micro<string, never, never>) => Micro.Micro<string, never, never>): Micro.Micro<...> (+21 overloads)
pipe
(
import Micro
Micro
.
const tap: <string, Micro.Micro<void, never, never>>(f: (a: string) => Micro.Micro<void, never, never>) => <E, R>(self: Micro.Micro<string, E, R>) => Micro.Micro<string, E, R> (+3 overloads)

Execute a side effect from the success value of the Micro effect.

It is similar to the andThen api, but the success value is ignored.

@since3.4.0

tap
(
const log: (message: string) => Micro.Micro<void, never, never>
log
))
})
import Micro
Micro
.
const runSync: <string, never>(effect: Micro.Micro<string, never, never>) => string

Attempt to execute the Micro effect synchronously and return the success value.

@since3.4.0

runSync
(
const program1: Micro.Micro<string, never, never>
program1
)
/*
Output:
success: 42
*/
const
const program2: Micro.Micro<string, never, never>
program2
=
import Micro
Micro
.
const matchEffect: <number, Error, never, string, never, never, string, never, never>(self: Micro.Micro<number, Error, never>, options: {
readonly onFailure: (e: Error) => Micro.Micro<string, never, never>;
readonly onSuccess: (a: number) => Micro.Micro<...>;
}) => Micro.Micro<...> (+1 overload)

@since3.4.6

matchEffect
(
const failure: Micro.Micro<number, Error, never>
failure
, {
onFailure: (e: Error) => Micro.Micro<string, never, never>
onFailure
: (
error: Error
error
) =>
import Micro
Micro
.
const succeed: <string>(value: string) => Micro.Micro<string, never, never>

Creates a Micro effect that will succeed with the specified constant value.

@since3.4.0

succeed
(`failure: ${
error: Error
error
.
Error.message: string
message
}`).
Pipeable.pipe<Micro.Micro<string, never, never>, Micro.Micro<string, never, never>>(this: Micro.Micro<...>, ab: (_: Micro.Micro<string, never, never>) => Micro.Micro<string, never, never>): Micro.Micro<...> (+21 overloads)
pipe
(
import Micro
Micro
.
const tap: <string, Micro.Micro<void, never, never>>(f: (a: string) => Micro.Micro<void, never, never>) => <E, R>(self: Micro.Micro<string, E, R>) => Micro.Micro<string, E, R> (+3 overloads)

Execute a side effect from the success value of the Micro effect.

It is similar to the andThen api, but the success value is ignored.

@since3.4.0

tap
(
const log: (message: string) => Micro.Micro<void, never, never>
log
)),
onSuccess: (a: number) => Micro.Micro<string, never, never>
onSuccess
: (
value: number
value
) =>
import Micro
Micro
.
const succeed: <string>(value: string) => Micro.Micro<string, never, never>

Creates a Micro effect that will succeed with the specified constant value.

@since3.4.0

succeed
(`success: ${
value: number
value
}`).
Pipeable.pipe<Micro.Micro<string, never, never>, Micro.Micro<string, never, never>>(this: Micro.Micro<...>, ab: (_: Micro.Micro<string, never, never>) => Micro.Micro<string, never, never>): Micro.Micro<...> (+21 overloads)
pipe
(
import Micro
Micro
.
const tap: <string, Micro.Micro<void, never, never>>(f: (a: string) => Micro.Micro<void, never, never>) => <E, R>(self: Micro.Micro<string, E, R>) => Micro.Micro<string, E, R> (+3 overloads)

Execute a side effect from the success value of the Micro effect.

It is similar to the andThen api, but the success value is ignored.

@since3.4.0

tap
(
const log: (message: string) => Micro.Micro<void, never, never>
log
))
})
import Micro
Micro
.
const runSync: <string, never>(effect: Micro.Micro<string, never, never>) => string

Attempt to execute the Micro effect synchronously and return the success value.

@since3.4.0

runSync
(
const program2: Micro.Micro<string, never, never>
program2
)
/*
Output:
failure: Uh oh!
*/

The Micro.matchCause and Micro.matchCauseEffect functions allow you to handle failures more precisely by providing access to the complete cause of failure within a fiber. This makes it possible to differentiate between various failure types and respond accordingly.

Example (Handling Different Failure Causes with Micro.matchCauseEffect)

import {
import Micro
Micro
} from "effect"
// Helper function to log a message
const
const log: (message: string) => Micro.Micro<void, never, never>
log
= (
message: string
message
: string) =>
import Micro
Micro
.
const sync: <void>(evaluate: LazyArg<void>) => Micro.Micro<void, never, never>

Creates a Micro effect that succeeds with a lazily evaluated value.

If the evaluation of the value throws an error, the effect will fail with a Die variant of the MicroCause type.

@since3.4.0

sync
(() =>
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
(
message: string
message
))
const
const task: Micro.Micro<number, Error, never>
task
:
import Micro
Micro
.
interface Micro<out A, out E = never, out R = never>

A lightweight alternative to the Effect data type, with a subset of the functionality.

@since3.4.0

@since3.4.0

Micro
<number,
interface Error
Error
> =
import Micro
Micro
.
const die: (defect: unknown) => Micro.Micro<never>

Creates a Micro effect that will die with the specified error.

This results in a Die variant of the MicroCause type, where the error is not tracked at the type level.

@since3.4.0

die
("Uh oh!")
const
const program: Micro.Micro<void, never, never>
program
=
import Micro
Micro
.
const matchCauseEffect: <number, Error, never, void, never, never, void, never, never>(self: Micro.Micro<number, Error, never>, options: {
readonly onFailure: (cause: Micro.MicroCause<Error>) => Micro.Micro<...>;
readonly onSuccess: (a: number) => Micro.Micro<...>;
}) => Micro.Micro<...> (+1 overload)

@since3.4.6

matchCauseEffect
(
const task: Micro.Micro<number, Error, never>
task
, {
onFailure: (cause: Micro.MicroCause<Error>) => Micro.Micro<void, never, never>
onFailure
: (
cause: Micro.MicroCause<Error>
cause
) => {
switch (
cause: Micro.MicroCause<Error>
cause
.
MicroCause<E>.Proto<Tag extends string, E>._tag: "Die" | "Interrupt" | "Fail"
_tag
) {
case "Fail":
// Handle standard failure with a logged message
return
const log: (message: string) => Micro.Micro<void, never, never>
log
(`Fail: ${
cause: Micro.MicroCause.Fail<Error>
cause
.
MicroCause<E>.Fail<Error>.error: Error
error
.
Error.message: string
message
}`)
case "Die":
// Handle defects (unexpected errors) by logging the defect
return
const log: (message: string) => Micro.Micro<void, never, never>
log
(`Die: ${
cause: Micro.MicroCause.Die
cause
.
MicroCause<E>.Die.defect: unknown
defect
}`)
case "Interrupt":
// Handle interruption
return
const log: (message: string) => Micro.Micro<void, never, never>
log
("Interrupt")
}
},
onSuccess: (a: number) => Micro.Micro<void, never, never>
onSuccess
: (
value: number
value
) =>
// Log success if the task completes successfully
const log: (message: string) => Micro.Micro<void, never, never>
log
(`succeeded with ${
value: number
value
} value`)
})
import Micro
Micro
.
const runSync: <void, never>(effect: Micro.Micro<void, never, never>) => void

Attempt to execute the Micro effect synchronously and return the success value.

@since3.4.0

runSync
(
const program: Micro.Micro<void, never, never>
program
)
// Output: "Die: Uh oh!"

The Micro.retry function allows you to retry a failing effect according to a defined policy.

Example (Retrying with a Fixed Delay)

import {
import Micro
Micro
} from "effect"
let
let count: number
count
= 0
// Simulates an effect with possible failures
const
const effect: Micro.Micro<string, Error, never>
effect
=
import Micro
Micro
.
const async: <string, Error, never>(register: (resume: (effect: Micro.Micro<string, Error, never>) => void, signal: AbortSignal) => void | Micro.Micro<void, never, never>) => Micro.Micro<...>

Create a Micro effect from an asynchronous computation.

You can return a cleanup effect that will be run when the effect is aborted. It is also passed an AbortSignal that is triggered when the effect is aborted.

@since3.4.0

async
<string,
interface Error
Error
>((
resume: (effect: Micro.Micro<string, Error, never>) => void
resume
) => {
if (
let count: number
count
<= 2) {
let count: number
count
++
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
("failure")
resume: (effect: Micro.Micro<string, Error, never>) => void
resume
(
import Micro
Micro
.
const fail: <Error>(error: Error) => Micro.Micro<never, Error, never>

Creates a Micro effect that fails with the given error.

This results in a Fail variant of the MicroCause type, where the error is tracked at the type level.

@since3.4.0

fail
(new
var Error: ErrorConstructor
new (message?: string) => Error
Error
()))
} else {
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
("success")
resume: (effect: Micro.Micro<string, Error, never>) => void
resume
(
import Micro
Micro
.
const succeed: <string>(value: string) => Micro.Micro<string, never, never>

Creates a Micro effect that will succeed with the specified constant value.

@since3.4.0

succeed
("yay!"))
}
})
// Define a repetition policy using a spaced delay between retries
const
const policy: Micro.MicroSchedule
policy
=
import Micro
Micro
.
const scheduleSpaced: (millis: number) => Micro.MicroSchedule

Create a MicroSchedule that will generate a constant delay.

@since3.4.6

scheduleSpaced
(100)
const
const repeated: Micro.Micro<string, Error, never>
repeated
=
import Micro
Micro
.
const retry: <string, Error, never>(self: Micro.Micro<string, Error, never>, options?: {
while?: Predicate<Error> | undefined;
times?: number | undefined;
schedule?: Micro.MicroSchedule | undefined;
} | undefined) => Micro.Micro<...> (+1 overload)

Retry the given Micro effect using the provided options.

@since3.4.0

retry
(
const effect: Micro.Micro<string, Error, never>
effect
, {
schedule?: Micro.MicroSchedule | undefined
schedule
:
const policy: Micro.MicroSchedule
policy
})
import Micro
Micro
.
const runPromise: <string, Error>(effect: Micro.Micro<string, Error, never>, options?: {
readonly signal?: AbortSignal | undefined;
readonly scheduler?: Micro.MicroScheduler | undefined;
} | undefined) => Promise<...>

Execute the Micro effect and return a Promise that resolves with the successful value of the computation.

@since3.4.0

runPromise
(
const repeated: Micro.Micro<string, Error, never>
repeated
).
Promise<string>.then<void, never>(onfulfilled?: ((value: string) => void | PromiseLike<void>) | null | undefined, onrejected?: ((reason: any) => PromiseLike<never>) | null | undefined): Promise<...>

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

@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:
failure
failure
failure
success
yay!
*/

When an operation does not finish within the specified duration, the behavior of the Micro.timeout depends on whether the operation is “uninterruptible”.

  1. Interruptible Operation: If the operation can be interrupted, it is terminated immediately once the timeout threshold is reached, resulting in a TimeoutException.

    import {
    import Micro
    Micro
    } from "effect"
    const
    const task: Micro.Micro<string, never, never>
    task
    =
    import Micro
    Micro
    .
    const gen: <unknown, YieldWrap<Micro.Micro<void, never, never>>, string>(...args: [self: unknown, body: (this: unknown) => Generator<YieldWrap<Micro.Micro<void, never, never>>, string, never>] | [body: ...]) => Micro.Micro<...>

    @since3.4.0

    gen
    (function* () {
    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
    ("Start processing...")
    yield*
    import Micro
    Micro
    .
    const sleep: (millis: number) => Micro.Micro<void>

    Create a Micro effect that will sleep for the specified duration.

    @since3.4.0

    sleep
    (2_000) // Simulates a delay in processing
    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
    ("Processing complete.")
    return "Result"
    })
    const
    const timedEffect: Micro.Micro<string, Micro.TimeoutException, never>
    timedEffect
    =
    const task: Micro.Micro<string, never, never>
    task
    .
    Pipeable.pipe<Micro.Micro<string, never, never>, Micro.Micro<string, Micro.TimeoutException, never>>(this: Micro.Micro<...>, ab: (_: Micro.Micro<string, never, never>) => Micro.Micro<string, Micro.TimeoutException, never>): Micro.Micro<...> (+21 overloads)
    pipe
    (
    import Micro
    Micro
    .
    const timeout: (millis: number) => <A, E, R>(self: Micro.Micro<A, E, R>) => Micro.Micro<A, E | Micro.TimeoutException, R> (+1 overload)

    Returns an effect that will timeout this effect, that will fail with a TimeoutException if the timeout elapses before the effect has produced a value.

    If the timeout elapses, the running effect will be safely interrupted.

    @since3.4.0

    timeout
    (1_000))
    import Micro
    Micro
    .
    const runPromiseExit: <string, Micro.TimeoutException>(effect: Micro.Micro<string, Micro.TimeoutException, never>, options?: {
    readonly signal?: AbortSignal | undefined;
    readonly scheduler?: Micro.MicroScheduler | undefined;
    } | undefined) => Promise<...>

    Execute the Micro effect and return a Promise that resolves with the MicroExit of the computation.

    @since3.4.6

    runPromiseExit
    (
    const timedEffect: Micro.Micro<string, Micro.TimeoutException, never>
    timedEffect
    ).
    Promise<MicroExit<string, TimeoutException>>.then<void, never>(onfulfilled?: ((value: Micro.MicroExit<string, Micro.TimeoutException>) => void | PromiseLike<void>) | null | undefined, onrejected?: ((reason: any) => PromiseLike<...>) | 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:
    Start processing...
    {
    "_id": "MicroExit",
    "_tag": "Failure",
    "cause": {
    "_tag": "Fail",
    "traces": [],
    "name": "(MicroCause.Fail) TimeoutException",
    "error": {
    "_tag": "TimeoutException"
    }
    }
    }
    */
  2. Uninterruptible Operation: If the operation is uninterruptible, it continues until completion before the TimeoutException is assessed.

    import {
    import Micro
    Micro
    } from "effect"
    const
    const task: Micro.Micro<string, never, never>
    task
    =
    import Micro
    Micro
    .
    const gen: <unknown, YieldWrap<Micro.Micro<void, never, never>>, string>(...args: [self: unknown, body: (this: unknown) => Generator<YieldWrap<Micro.Micro<void, never, never>>, string, never>] | [body: ...]) => Micro.Micro<...>

    @since3.4.0

    gen
    (function* () {
    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
    ("Start processing...")
    yield*
    import Micro
    Micro
    .
    const sleep: (millis: number) => Micro.Micro<void>

    Create a Micro effect that will sleep for the specified duration.

    @since3.4.0

    sleep
    (2_000) // Simulates a delay in processing
    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
    ("Processing complete.")
    return "Result"
    })
    const
    const timedEffect: Micro.Micro<string, Micro.TimeoutException, never>
    timedEffect
    =
    const task: Micro.Micro<string, never, never>
    task
    .
    Pipeable.pipe<Micro.Micro<string, never, never>, Micro.Micro<string, never, never>, Micro.Micro<string, Micro.TimeoutException, never>>(this: Micro.Micro<...>, ab: (_: Micro.Micro<string, never, never>) => Micro.Micro<...>, bc: (_: Micro.Micro<...>) => Micro.Micro<...>): Micro.Micro<...> (+21 overloads)
    pipe
    (
    import Micro
    Micro
    .
    const uninterruptible: <A, E, R>(self: Micro.Micro<A, E, R>) => Micro.Micro<A, E, R>

    Flag the effect as uninterruptible, which means that when the effect is interrupted, it will be allowed to continue running until completion.

    @since3.4.0

    uninterruptible
    ,
    import Micro
    Micro
    .
    const timeout: (millis: number) => <A, E, R>(self: Micro.Micro<A, E, R>) => Micro.Micro<A, E | Micro.TimeoutException, R> (+1 overload)

    Returns an effect that will timeout this effect, that will fail with a TimeoutException if the timeout elapses before the effect has produced a value.

    If the timeout elapses, the running effect will be safely interrupted.

    @since3.4.0

    timeout
    (1_000)
    )
    // Outputs a TimeoutException after the task completes,
    // because the task is uninterruptible
    import Micro
    Micro
    .
    const runPromiseExit: <string, Micro.TimeoutException>(effect: Micro.Micro<string, Micro.TimeoutException, never>, options?: {
    readonly signal?: AbortSignal | undefined;
    readonly scheduler?: Micro.MicroScheduler | undefined;
    } | undefined) => Promise<...>

    Execute the Micro effect and return a Promise that resolves with the MicroExit of the computation.

    @since3.4.6

    runPromiseExit
    (
    const timedEffect: Micro.Micro<string, Micro.TimeoutException, never>
    timedEffect
    ).
    Promise<MicroExit<string, TimeoutException>>.then<void, never>(onfulfilled?: ((value: Micro.MicroExit<string, Micro.TimeoutException>) => void | PromiseLike<void>) | null | undefined, onrejected?: ((reason: any) => PromiseLike<...>) | 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:
    Start processing...
    Processing complete.
    {
    "_id": "MicroExit",
    "_tag": "Failure",
    "cause": {
    "_tag": "Fail",
    "traces": [],
    "name": "(MicroCause.Fail) TimeoutException",
    "error": {
    "_tag": "TimeoutException"
    }
    }
    }
    */

The Micro.sandbox function allows you to encapsulate all the potential causes of an error in an effect. It exposes the full cause of an effect, whether it’s due to a failure, defect or interruption.

In simple terms, it takes an effect Micro<A, E, R> and transforms it into an effect Micro<A, MicroCause<E>, R> where the error channel now contains a detailed cause of the error.

import {
import Micro
Micro
} from "effect"
// Helper function to log a message
const
const log: (message: string) => Micro.Micro<void, never, never>
log
= (
message: string
message
: string) =>
import Micro
Micro
.
const sync: <void>(evaluate: LazyArg<void>) => Micro.Micro<void, never, never>

Creates a Micro effect that succeeds with a lazily evaluated value.

If the evaluation of the value throws an error, the effect will fail with a Die variant of the MicroCause type.

@since3.4.0

sync
(() =>
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
(
message: string
message
))
// ┌─── Micro<string, Error, never>
// ▼
const
const task: Micro.Micro<string, Error, never>
task
=
import Micro
Micro
.
const fail: <Error>(error: Error) => Micro.Micro<never, Error, never>

Creates a Micro effect that fails with the given error.

This results in a Fail variant of the MicroCause type, where the error is tracked at the type level.

@since3.4.0

fail
(new
var Error: ErrorConstructor
new (message?: string) => Error
Error
("Oh uh!")).
Pipeable.pipe<Micro.Micro<never, Error, never>, Micro.Micro<string, Error, never>>(this: Micro.Micro<...>, ab: (_: Micro.Micro<never, Error, never>) => Micro.Micro<string, Error, never>): Micro.Micro<...> (+21 overloads)
pipe
(
import Micro
Micro
.
const as: <never, string>(value: string) => <E, R>(self: Micro.Micro<never, E, R>) => Micro.Micro<string, E, R> (+1 overload)

Create a Micro effect that will replace the success value of the given effect.

@since3.4.0

as
("primary result")
)
// ┌─── Effect<string, MicroCause<Error>, never>
// ▼
const
const sandboxed: Micro.Micro<string, Micro.MicroCause<Error>, never>
sandboxed
=
import Micro
Micro
.
const sandbox: <string, Error, never>(self: Micro.Micro<string, Error, never>) => Micro.Micro<string, Micro.MicroCause<Error>, never>

Replace the error type of the given Micro with the full MicroCause object.

@since3.4.0

sandbox
(
const task: Micro.Micro<string, Error, never>
task
)
const
const program: Micro.Micro<string, never, never>
program
=
const sandboxed: Micro.Micro<string, Micro.MicroCause<Error>, never>
sandboxed
.
Pipeable.pipe<Micro.Micro<string, Micro.MicroCause<Error>, never>, Micro.Micro<string, Micro.MicroCause<E>.Die | Micro.MicroCause.Interrupt, never>, Micro.Micro<...>, Micro.Micro<...>>(this: Micro.Micro<...>, ab: (_: Micro.Micro<...>) => Micro.Micro<...>, bc: (_: Micro.Micro<...>) => Micro.Micro<...>, cd: (_: Micro.Micro<...>) => Micro.Micro<...>): Micro.Micro<...> (+21 overloads)
pipe
(
import Micro
Micro
.
const catchTag: <"Fail", Micro.MicroCause<Error>, string, never, never>(k: "Fail", f: (e: Micro.MicroCause<E>.Fail<Error>) => Micro.Micro<string, never, never>) => <A, R>(self: Micro.Micro<...>) => Micro.Micro<...> (+1 overload)

Recovers from the specified tagged error.

@since3.4.0

catchTag
("Fail", (
cause: Micro.MicroCause.Fail<Error>
cause
) =>
const log: (message: string) => Micro.Micro<void, never, never>
log
(`Caught a defect: ${
cause: Micro.MicroCause.Fail<Error>
cause
.
MicroCause<E>.Fail<Error>.error: Error
error
}`).
Pipeable.pipe<Micro.Micro<void, never, never>, Micro.Micro<string, never, never>>(this: Micro.Micro<...>, ab: (_: Micro.Micro<void, never, never>) => Micro.Micro<string, never, never>): Micro.Micro<...> (+21 overloads)
pipe
(
import Micro
Micro
.
const as: <void, string>(value: string) => <E, R>(self: Micro.Micro<void, E, R>) => Micro.Micro<string, E, R> (+1 overload)

Create a Micro effect that will replace the success value of the given effect.

@since3.4.0

as
("fallback result on expected error")
)
),
import Micro
Micro
.
const catchTag: <"Interrupt", Micro.MicroCause<E>.Die | Micro.MicroCause.Interrupt, string, never, never>(k: "Interrupt", f: (e: Micro.MicroCause.Interrupt) => Micro.Micro<string, never, never>) => <A, R>(self: Micro.Micro<...>) => Micro.Micro<...> (+1 overload)

Recovers from the specified tagged error.

@since3.4.0

catchTag
("Interrupt", () =>
const log: (message: string) => Micro.Micro<void, never, never>
log
(`Caught a defect`).
Pipeable.pipe<Micro.Micro<void, never, never>, Micro.Micro<string, never, never>>(this: Micro.Micro<...>, ab: (_: Micro.Micro<void, never, never>) => Micro.Micro<string, never, never>): Micro.Micro<...> (+21 overloads)
pipe
(
import Micro
Micro
.
const as: <void, string>(value: string) => <E, R>(self: Micro.Micro<void, E, R>) => Micro.Micro<string, E, R> (+1 overload)

Create a Micro effect that will replace the success value of the given effect.

@since3.4.0

as
("fallback result on fiber interruption")
)
),
import Micro
Micro
.
const catchTag: <"Die", Micro.MicroCause<E>.Die, string, never, never>(k: "Die", f: (e: Micro.MicroCause.Die) => Micro.Micro<string, never, never>) => <A, R>(self: Micro.Micro<A, Micro.MicroCause.Die, R>) => Micro.Micro<...> (+1 overload)

Recovers from the specified tagged error.

@since3.4.0

catchTag
("Die", (
cause: Micro.MicroCause.Die
cause
) =>
const log: (message: string) => Micro.Micro<void, never, never>
log
(`Caught a defect: ${
cause: Micro.MicroCause.Die
cause
.
MicroCause<E>.Die.defect: unknown
defect
}`).
Pipeable.pipe<Micro.Micro<void, never, never>, Micro.Micro<string, never, never>>(this: Micro.Micro<...>, ab: (_: Micro.Micro<void, never, never>) => Micro.Micro<string, never, never>): Micro.Micro<...> (+21 overloads)
pipe
(
import Micro
Micro
.
const as: <void, string>(value: string) => <E, R>(self: Micro.Micro<void, E, R>) => Micro.Micro<string, E, R> (+1 overload)

Create a Micro effect that will replace the success value of the given effect.

@since3.4.0

as
("fallback result on unexpected error")
)
)
)
import Micro
Micro
.
const runPromise: <string, never>(effect: Micro.Micro<string, never, never>, options?: {
readonly signal?: AbortSignal | undefined;
readonly scheduler?: Micro.MicroScheduler | undefined;
} | undefined) => Promise<...>

Execute the Micro effect and return a Promise that resolves with the successful value of the computation.

@since3.4.0

runPromise
(
const program: Micro.Micro<string, never, never>
program
).
Promise<string>.then<void, never>(onfulfilled?: ((value: string) => void | PromiseLike<void>) | null | undefined, onrejected?: ((reason: any) => PromiseLike<never>) | null | undefined): Promise<...>

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

@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:
Caught a defect: Error: Oh uh!
fallback result on expected error
*/

Executes an effectful operation to inspect the failure of an effect without altering it.

Example (Inspecting Errors)

import {
import Micro
Micro
} from "effect"
// Helper function to log a message
const
const log: (message: string) => Micro.Micro<void, never, never>
log
= (
message: string
message
: string) =>
import Micro
Micro
.
const sync: <void>(evaluate: LazyArg<void>) => Micro.Micro<void, never, never>

Creates a Micro effect that succeeds with a lazily evaluated value.

If the evaluation of the value throws an error, the effect will fail with a Die variant of the MicroCause type.

@since3.4.0

sync
(() =>
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
(
message: string
message
))
// Simulate a task that fails with an error
const
const task: Micro.Micro<number, string, never>
task
:
import Micro
Micro
.
interface Micro<out A, out E = never, out R = never>

A lightweight alternative to the Effect data type, with a subset of the functionality.

@since3.4.0

@since3.4.0

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

Creates a Micro effect that fails with the given error.

This results in a Fail variant of the MicroCause type, where the error is tracked at the type level.

@since3.4.0

fail
("NetworkError")
// Use tapError to log the error message when the task fails
const
const tapping: Micro.Micro<number, string, never>
tapping
=
import Micro
Micro
.
const tapError: <number, string, never, void, never, never>(self: Micro.Micro<number, string, never>, f: (e: string) => Micro.Micro<void, never, never>) => Micro.Micro<number, string, never> (+1 overload)

Perform a side effect from expected errors of the given Micro.

@since3.4.6

tapError
(
const task: Micro.Micro<number, string, never>
task
, (
error: string
error
) =>
const log: (message: string) => Micro.Micro<void, never, never>
log
(`expected error: ${
error: string
error
}`)
)
import Micro
Micro
.
const runFork: <number, string>(effect: Micro.Micro<number, string, never>, options?: {
readonly signal?: AbortSignal | undefined;
readonly scheduler?: Micro.MicroScheduler | undefined;
} | undefined) => MicroFiberImpl<...>

Execute the Micro effect and return a MicroFiber that can be awaited, joined, or aborted.

You can listen for the result by adding an observer using the handle's addObserver method.

@example

import * as Micro from "effect/Micro"
const handle = Micro.succeed(42).pipe(
Micro.delay(1000),
Micro.runFork
)
handle.addObserver((exit) => {
console.log(exit)
})

@since3.4.0

runFork
(
const tapping: Micro.Micro<number, string, never>
tapping
)
/*
Output:
expected error: NetworkError
*/

This function inspects the complete cause of an error, including failures and defects.

Example (Inspecting Error Causes)

import {
import Micro
Micro
} from "effect"
// Helper function to log a message
const
const log: (message: string) => Micro.Micro<void, never, never>
log
= (
message: string
message
: string) =>
import Micro
Micro
.
const sync: <void>(evaluate: LazyArg<void>) => Micro.Micro<void, never, never>

Creates a Micro effect that succeeds with a lazily evaluated value.

If the evaluation of the value throws an error, the effect will fail with a Die variant of the MicroCause type.

@since3.4.0

sync
(() =>
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
(
message: string
message
))
// Create a task that fails with a NetworkError
const
const task1: Micro.Micro<number, string, never>
task1
:
import Micro
Micro
.
interface Micro<out A, out E = never, out R = never>

A lightweight alternative to the Effect data type, with a subset of the functionality.

@since3.4.0

@since3.4.0

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

Creates a Micro effect that fails with the given error.

This results in a Fail variant of the MicroCause type, where the error is tracked at the type level.

@since3.4.0

fail
("NetworkError")
const
const tapping1: Micro.Micro<number, string, never>
tapping1
=
import Micro
Micro
.
const tapErrorCause: <number, string, never, void, never, never>(self: Micro.Micro<number, string, never>, f: (cause: NoInfer<Micro.MicroCause<string>>) => Micro.Micro<void, never, never>) => Micro.Micro<...> (+1 overload)

Perform a side effect using the full MicroCause object of the given Micro.

@since3.4.6

tapErrorCause
(
const task1: Micro.Micro<number, string, never>
task1
, (
cause: NoInfer<Micro.MicroCause<string>>
cause
) =>
const log: (message: string) => Micro.Micro<void, never, never>
log
(`error cause: ${
cause: Micro.MicroCause<string>
cause
}`)
)
import Micro
Micro
.
const runFork: <number, string>(effect: Micro.Micro<number, string, never>, options?: {
readonly signal?: AbortSignal | undefined;
readonly scheduler?: Micro.MicroScheduler | undefined;
} | undefined) => MicroFiberImpl<...>

Execute the Micro effect and return a MicroFiber that can be awaited, joined, or aborted.

You can listen for the result by adding an observer using the handle's addObserver method.

@example

import * as Micro from "effect/Micro"
const handle = Micro.succeed(42).pipe(
Micro.delay(1000),
Micro.runFork
)
handle.addObserver((exit) => {
console.log(exit)
})

@since3.4.0

runFork
(
const tapping1: Micro.Micro<number, string, never>
tapping1
)
/*
Output:
error cause: MicroCause.Fail: NetworkError
*/
// Simulate a severe failure in the system
const
const task2: Micro.Micro<number, string, never>
task2
:
import Micro
Micro
.
interface Micro<out A, out E = never, out R = never>

A lightweight alternative to the Effect data type, with a subset of the functionality.

@since3.4.0

@since3.4.0

Micro
<number, string> =
import Micro
Micro
.
const die: (defect: unknown) => Micro.Micro<never>

Creates a Micro effect that will die with the specified error.

This results in a Die variant of the MicroCause type, where the error is not tracked at the type level.

@since3.4.0

die
(
"Something went wrong"
)
const
const tapping2: Micro.Micro<number, string, never>
tapping2
=
import Micro
Micro
.
const tapErrorCause: <number, string, never, void, never, never>(self: Micro.Micro<number, string, never>, f: (cause: NoInfer<Micro.MicroCause<string>>) => Micro.Micro<void, never, never>) => Micro.Micro<...> (+1 overload)

Perform a side effect using the full MicroCause object of the given Micro.

@since3.4.6

tapErrorCause
(
const task2: Micro.Micro<number, string, never>
task2
, (
cause: NoInfer<Micro.MicroCause<string>>
cause
) =>
const log: (message: string) => Micro.Micro<void, never, never>
log
(`error cause: ${
cause: Micro.MicroCause<string>
cause
}`)
)
import Micro
Micro
.
const runFork: <number, string>(effect: Micro.Micro<number, string, never>, options?: {
readonly signal?: AbortSignal | undefined;
readonly scheduler?: Micro.MicroScheduler | undefined;
} | undefined) => MicroFiberImpl<...>

Execute the Micro effect and return a MicroFiber that can be awaited, joined, or aborted.

You can listen for the result by adding an observer using the handle's addObserver method.

@example

import * as Micro from "effect/Micro"
const handle = Micro.succeed(42).pipe(
Micro.delay(1000),
Micro.runFork
)
handle.addObserver((exit) => {
console.log(exit)
})

@since3.4.0

runFork
(
const tapping2: Micro.Micro<number, string, never>
tapping2
)
/*
Output:
error cause: MicroCause.Die: Something went wrong
*/

Specifically inspects non-recoverable failures or defects in an effect (i.e., one or more Die causes).

Example (Inspecting Defects)

import {
import Micro
Micro
} from "effect"
// Helper function to log a message
const
const log: (message: string) => Micro.Micro<void, never, never>
log
= (
message: string
message
: string) =>
import Micro
Micro
.
const sync: <void>(evaluate: LazyArg<void>) => Micro.Micro<void, never, never>

Creates a Micro effect that succeeds with a lazily evaluated value.

If the evaluation of the value throws an error, the effect will fail with a Die variant of the MicroCause type.

@since3.4.0

sync
(() =>
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
(
message: string
message
))
// Simulate a task that fails with a recoverable error
const
const task1: Micro.Micro<number, string, never>
task1
:
import Micro
Micro
.
interface Micro<out A, out E = never, out R = never>

A lightweight alternative to the Effect data type, with a subset of the functionality.

@since3.4.0

@since3.4.0

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

Creates a Micro effect that fails with the given error.

This results in a Fail variant of the MicroCause type, where the error is tracked at the type level.

@since3.4.0

fail
("NetworkError")
// tapDefect won't log anything because NetworkError is not a defect
const
const tapping1: Micro.Micro<number, string, never>
tapping1
=
import Micro
Micro
.
const tapDefect: <number, string, never, void, never, never>(self: Micro.Micro<number, string, never>, f: (defect: unknown) => Micro.Micro<void, never, never>) => Micro.Micro<number, string, never> (+1 overload)

Perform a side effect from unexpected errors of the given Micro.

@since3.4.6

tapDefect
(
const task1: Micro.Micro<number, string, never>
task1
, (
cause: unknown
cause
) =>
const log: (message: string) => Micro.Micro<void, never, never>
log
(`defect: ${
cause: unknown
cause
}`)
)
import Micro
Micro
.
const runFork: <number, string>(effect: Micro.Micro<number, string, never>, options?: {
readonly signal?: AbortSignal | undefined;
readonly scheduler?: Micro.MicroScheduler | undefined;
} | undefined) => MicroFiberImpl<...>

Execute the Micro effect and return a MicroFiber that can be awaited, joined, or aborted.

You can listen for the result by adding an observer using the handle's addObserver method.

@example

import * as Micro from "effect/Micro"
const handle = Micro.succeed(42).pipe(
Micro.delay(1000),
Micro.runFork
)
handle.addObserver((exit) => {
console.log(exit)
})

@since3.4.0

runFork
(
const tapping1: Micro.Micro<number, string, never>
tapping1
)
/*
No Output
*/
// Simulate a severe failure in the system
const
const task2: Micro.Micro<number, string, never>
task2
:
import Micro
Micro
.
interface Micro<out A, out E = never, out R = never>

A lightweight alternative to the Effect data type, with a subset of the functionality.

@since3.4.0

@since3.4.0

Micro
<number, string> =
import Micro
Micro
.
const die: (defect: unknown) => Micro.Micro<never>

Creates a Micro effect that will die with the specified error.

This results in a Die variant of the MicroCause type, where the error is not tracked at the type level.

@since3.4.0

die
(
"Something went wrong"
)
// Log the defect using tapDefect
const
const tapping2: Micro.Micro<number, string, never>
tapping2
=
import Micro
Micro
.
const tapDefect: <number, string, never, void, never, never>(self: Micro.Micro<number, string, never>, f: (defect: unknown) => Micro.Micro<void, never, never>) => Micro.Micro<number, string, never> (+1 overload)

Perform a side effect from unexpected errors of the given Micro.

@since3.4.6

tapDefect
(
const task2: Micro.Micro<number, string, never>
task2
, (
cause: unknown
cause
) =>
const log: (message: string) => Micro.Micro<void, never, never>
log
(`defect: ${
cause: unknown
cause
}`)
)
import Micro
Micro
.
const runFork: <number, string>(effect: Micro.Micro<number, string, never>, options?: {
readonly signal?: AbortSignal | undefined;
readonly scheduler?: Micro.MicroScheduler | undefined;
} | undefined) => MicroFiberImpl<...>

Execute the Micro effect and return a MicroFiber that can be awaited, joined, or aborted.

You can listen for the result by adding an observer using the handle's addObserver method.

@example

import * as Micro from "effect/Micro"
const handle = Micro.succeed(42).pipe(
Micro.delay(1000),
Micro.runFork
)
handle.addObserver((exit) => {
console.log(exit)
})

@since3.4.0

runFork
(
const tapping2: Micro.Micro<number, string, never>
tapping2
)
/*
Output:
defect: Something went wrong
*/

Yieldable Errors are special types of errors that can be yielded directly within a generator function using Micro.gen. These errors allow you to handle them intuitively, without needing to explicitly invoke Micro.fail. This simplifies how you manage custom errors in your code.

The Error constructor provides a way to define a base class for yieldable errors.

Example (Creating and Yielding a Custom Error)

import {
import Micro
Micro
} from "effect"
// Define a custom error class extending Error
class
class MyError
MyError
extends
import Micro
Micro
.
const Error: new <A extends Record<string, any> = {}>(args: Equals<A, {}> extends true ? void : { readonly [P in keyof A]: A[P]; }) => Micro.YieldableError & Readonly<A>

@since3.4.0

Error
<{
message: string
message
: string }> {}
export const
const program: Micro.Micro<void, MyError, never>
program
=
import Micro
Micro
.
const gen: <unknown, YieldWrap<Micro.Micro<never, MyError, never>>, void>(...args: [self: unknown, body: (this: unknown) => Generator<YieldWrap<Micro.Micro<never, MyError, never>>, void, never>] | [body: ...]) => Micro.Micro<...>

@since3.4.0

gen
(function* () {
// Yield a custom error (equivalent to failing with MyError)
yield* new
constructor MyError<{
message: string;
}>(args: {
readonly message: string;
}): MyError

@since3.4.0

MyError
({
message: string
message
: "Oh no!" })
})
import Micro
Micro
.
const runPromiseExit: <void, MyError>(effect: Micro.Micro<void, MyError, never>, options?: {
readonly signal?: AbortSignal | undefined;
readonly scheduler?: Micro.MicroScheduler | undefined;
} | undefined) => Promise<...>

Execute the Micro effect and return a Promise that resolves with the MicroExit of the computation.

@since3.4.6

runPromiseExit
(
const program: Micro.Micro<void, MyError, never>
program
).
Promise<MicroExit<void, MyError>>.then<void, never>(onfulfilled?: ((value: Micro.MicroExit<void, MyError>) => 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": "MicroExit",
"_tag": "Failure",
"cause": {
"_tag": "Fail",
"traces": [],
"name": "(MicroCause.Fail) Error",
"error": {
"message": "Oh no!"
}
}
}
*/

The TaggedError constructor lets you define custom yieldable errors with unique tags. Each error has a _tag property, allowing you to easily distinguish between different error types. This makes it convenient to handle specific tagged errors using functions like Micro.catchTag.

Example (Handling Multiple Tagged Errors)

import {
import Micro
Micro
} from "effect"
// An error with _tag: "Foo"
class
class FooError
FooError
extends
import Micro
Micro
.
const TaggedError: <"Foo">(tag: "Foo") => new <A>(args: Equals<A, {}> extends true ? void : { readonly [P in keyof A as P extends "_tag" ? never : P]: A[P]; }) => Micro.YieldableError & {
...;
} & Readonly<...>

@since3.4.0

TaggedError
("Foo")<{
message: string
message
: string
}> {}
// An error with _tag: "Bar"
class
class BarError
BarError
extends
import Micro
Micro
.
const TaggedError: <"Bar">(tag: "Bar") => new <A>(args: Equals<A, {}> extends true ? void : { readonly [P in keyof A as P extends "_tag" ? never : P]: A[P]; }) => Micro.YieldableError & {
...;
} & Readonly<...>

@since3.4.0

TaggedError
("Bar")<{
randomNumber: number
randomNumber
: number
}> {}
export const
const program: Micro.Micro<string, never, never>
program
=
import Micro
Micro
.
const gen: <unknown, YieldWrap<Micro.Micro<never, FooError, never>> | YieldWrap<Micro.Micro<never, BarError, never>>, string>(...args: [self: ...] | [body: ...]) => Micro.Micro<...>

@since3.4.0

gen
(function* () {
const
const n: number
n
=
var Math: Math

An intrinsic object that provides basic mathematics functionality and constants.

Math
.
Math.random(): number

Returns a pseudorandom number between 0 and 1.

random
()
return
const n: number
n
> 0.5
? "yay!"
:
const n: number
n
< 0.2
? yield* new
constructor FooError<{
message: string;
}>(args: {
readonly message: string;
}): FooError
FooError
({
message: string
message
: "Oh no!" })
: yield* new
constructor BarError<{
randomNumber: number;
}>(args: {
readonly randomNumber: number;
}): BarError
BarError
({
randomNumber: number
randomNumber
:
const n: number
n
})
}).
Pipeable.pipe<Micro.Micro<string, FooError | BarError, never>, Micro.Micro<string, BarError, never>, Micro.Micro<string, never, never>>(this: Micro.Micro<...>, ab: (_: Micro.Micro<...>) => Micro.Micro<...>, bc: (_: Micro.Micro<...>) => Micro.Micro<...>): Micro.Micro<...> (+21 overloads)
pipe
(
// Handle different tagged errors using catchTag
import Micro
Micro
.
const catchTag: <"Foo", FooError | BarError, string, never, never>(k: "Foo", f: (e: FooError) => Micro.Micro<string, never, never>) => <A, R>(self: Micro.Micro<A, FooError | BarError, R>) => Micro.Micro<...> (+1 overload)

Recovers from the specified tagged error.

@since3.4.0

catchTag
("Foo", (
error: FooError
error
) =>
import Micro
Micro
.
const succeed: <string>(value: string) => Micro.Micro<string, never, never>

Creates a Micro effect that will succeed with the specified constant value.

@since3.4.0

succeed
(`Foo error: ${
error: FooError
error
.
message: string
message
}`)
),
import Micro
Micro
.
const catchTag: <"Bar", BarError, string, never, never>(k: "Bar", f: (e: BarError) => Micro.Micro<string, never, never>) => <A, R>(self: Micro.Micro<A, BarError, R>) => Micro.Micro<...> (+1 overload)

Recovers from the specified tagged error.

@since3.4.0

catchTag
("Bar", (
error: BarError
error
) =>
import Micro
Micro
.
const succeed: <string>(value: string) => Micro.Micro<string, never, never>

Creates a Micro effect that will succeed with the specified constant value.

@since3.4.0

succeed
(`Bar error: ${
error: BarError
error
.
randomNumber: number
randomNumber
}`)
)
)
import Micro
Micro
.
const runPromise: <string, never>(effect: Micro.Micro<string, never, never>, options?: {
readonly signal?: AbortSignal | undefined;
readonly scheduler?: Micro.MicroScheduler | undefined;
} | undefined) => Promise<...>

Execute the Micro effect and return a Promise that resolves with the successful value of the computation.

@since3.4.0

runPromise
(
const program: Micro.Micro<string, never, never>
program
).
Promise<string>.then<void, void>(onfulfilled?: ((value: string) => void | PromiseLike<void>) | null | undefined, onrejected?: ((reason: any) => void | PromiseLike<void>) | 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
,
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.error(message?: any, ...optionalParams: any[]): void

Prints to stderr 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 code = 5;
console.error('error #%d', code);
// Prints: error #5, to stderr
console.error('error', code);
// Prints: error 5, to stderr

If formatting elements (e.g. %d) are not found in the first string then util.inspect() is called on each argument and the resulting string values are concatenated. See util.format() for more information.

@sincev0.1.100

error
)
/*
Example Output (n < 0.2):
Foo error: Oh no!
*/

In the context of programming, a service refers to a reusable component or functionality that can be used by different parts of an application. Services are designed to provide specific capabilities and can be shared across multiple modules or components.

Services often encapsulate common tasks or operations that are needed by different parts of an application. They can handle complex operations, interact with external systems or APIs, manage data, or perform other specialized tasks.

Services are typically designed to be modular and decoupled from the rest of the application. This allows them to be easily maintained, tested, and replaced without affecting the overall functionality of the application.

To create a new service, you need two things:

  • A unique identifier.
  • A type describing the possible operations of the service.
import {
import Micro
Micro
,
import Context

@since2.0.0

@since2.0.0

Context
} from "effect"
// Declaring a tag for a service that generates random numbers
class
class Random
Random
extends
import Context

@since2.0.0

@since2.0.0

Context
.
const Tag: <"MyRandomService">(id: "MyRandomService") => <Self, Shape>() => Context.TagClass<Self, "MyRandomService", 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
("MyRandomService")<
class Random
Random
,
{ readonly
next: Micro.Micro<number, never, never>
next
:
import Micro
Micro
.
interface Micro<out A, out E = never, out R = never>

A lightweight alternative to the Effect data type, with a subset of the functionality.

@since3.4.0

@since3.4.0

Micro
<number> }
>() {}

Now that we have our service tag defined, let’s see how we can use it by building a simple program.

Example (Using a Custom Service in a Program)

import * as
import Context

@since2.0.0

@since2.0.0

Context
from "effect/Context"
import {
import Micro
Micro
} from "effect"
// Declaring a tag for a service that generates random numbers
class
class Random
Random
extends
import Context

@since2.0.0

@since2.0.0

Context
.
const Tag: <"MyRandomService">(id: "MyRandomService") => <Self, Shape>() => Context.TagClass<Self, "MyRandomService", 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
("MyRandomService")<
class Random
Random
,
{ readonly
next: Micro.Micro<number, never, never>
next
:
import Micro
Micro
.
interface Micro<out A, out E = never, out R = never>

A lightweight alternative to the Effect data type, with a subset of the functionality.

@since3.4.0

@since3.4.0

Micro
<number> }
>() {}
// Using the service
//
// ┌─── Micro<void, never, Random>
// ▼
const
const program: Micro.Micro<void, never, Random>
program
=
import Micro
Micro
.
const gen: <unknown, YieldWrap<Micro.Micro<{
readonly next: Micro.Micro<number>;
}, never, Random>> | YieldWrap<Micro.Micro<number, never, never>>, void>(...args: [self: ...] | [body: ...]) => Micro.Micro<...>

@since3.4.0

gen
(function* () {
// Access the Random service
const
const random: {
readonly next: Micro.Micro<number>;
}
random
= yield*
import Micro
Micro
.
const service: <Random, {
readonly next: Micro.Micro<number>;
}>(tag: Context.Tag<Random, {
readonly next: Micro.Micro<number>;
}>) => Micro.Micro<{
readonly next: Micro.Micro<number>;
}, never, Random> (+1 overload)

Access the given Context.Tag from the environment.

@since3.4.0

service
(
class Random
Random
)
// Retrieve a random number from the service
const
const randomNumber: number
randomNumber
= yield*
const random: {
readonly next: Micro.Micro<number>;
}
random
.
next: Micro.Micro<number, never, never>
next
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
(`random number: ${
const randomNumber: number
randomNumber
}`)
})

It’s worth noting that the type of the program variable includes Random in the Requirements type parameter:

const program: Micro<void, never, Random>

This indicates that our program requires the Random service to be provided in order to execute successfully.

To successfully execute the program, we need to provide an actual implementation of the Random service.

Example (Providing and Using a Service)

import {
import Micro
Micro
,
import Context

@since2.0.0

@since2.0.0

Context
} from "effect"
// Declaring a tag for a service that generates random numbers
class
class Random
Random
extends
import Context

@since2.0.0

@since2.0.0

Context
.
const Tag: <"MyRandomService">(id: "MyRandomService") => <Self, Shape>() => Context.TagClass<Self, "MyRandomService", 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
("MyRandomService")<
class Random
Random
,
{ readonly
next: Micro.Micro<number, never, never>
next
:
import Micro
Micro
.
interface Micro<out A, out E = never, out R = never>

A lightweight alternative to the Effect data type, with a subset of the functionality.

@since3.4.0

@since3.4.0

Micro
<number> }
>() {}
// Using the service
const
const program: Micro.Micro<void, never, Random>
program
=
import Micro
Micro
.
const gen: <unknown, YieldWrap<Micro.Micro<{
readonly next: Micro.Micro<number>;
}, never, Random>> | YieldWrap<Micro.Micro<number, never, never>>, void>(...args: [self: ...] | [body: ...]) => Micro.Micro<...>

@since3.4.0

gen
(function* () {
// Access the Random service
const
const random: {
readonly next: Micro.Micro<number>;
}
random
= yield*
import Micro
Micro
.
const service: <Random, {
readonly next: Micro.Micro<number>;
}>(tag: Context.Tag<Random, {
readonly next: Micro.Micro<number>;
}>) => Micro.Micro<{
readonly next: Micro.Micro<number>;
}, never, Random> (+1 overload)

Access the given Context.Tag from the environment.

@since3.4.0

service
(
class Random
Random
)
// Retrieve a random number from the service
const
const randomNumber: number
randomNumber
= yield*
const random: {
readonly next: Micro.Micro<number>;
}
random
.
next: Micro.Micro<number, never, never>
next
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
(`random number: ${
const randomNumber: number
randomNumber
}`)
})
// Providing the implementation
//
// ┌─── Micro<void, never, never>
// ▼
const
const runnable: Micro.Micro<void, never, never>
runnable
=
import Micro
Micro
.
const provideService: <void, never, Random, Random, {
next: Micro.Micro<number, never, never>;
}>(self: Micro.Micro<void, never, Random>, tag: Context.Tag<Random, {
next: Micro.Micro<number, never, never>;
}>, service: {
next: Micro.Micro<number, never, never>;
}) => Micro.Micro<...> (+1 overload)

Add the provided service to the current context.

@since3.4.0

provideService
(
const program: Micro.Micro<void, never, Random>
program
,
class Random
Random
, {
next: Micro.Micro<number, never, never>
next
:
import Micro
Micro
.
const sync: <number>(evaluate: LazyArg<number>) => Micro.Micro<number, never, never>

Creates a Micro effect that succeeds with a lazily evaluated value.

If the evaluation of the value throws an error, the effect will fail with a Die variant of the MicroCause type.

@since3.4.0

sync
(() =>
var Math: Math

An intrinsic object that provides basic mathematics functionality and constants.

Math
.
Math.random(): number

Returns a pseudorandom number between 0 and 1.

random
())
})
import Micro
Micro
.
const runPromise: <void, never>(effect: Micro.Micro<void, never, never>, options?: {
readonly signal?: AbortSignal | undefined;
readonly scheduler?: Micro.MicroScheduler | undefined;
} | undefined) => Promise<...>

Execute the Micro effect and return a Promise that resolves with the successful value of the computation.

@since3.4.0

runPromise
(
const runnable: Micro.Micro<void, never, never>
runnable
)
/*
Example Output:
random number: 0.8241872233134417
*/

In simple terms, a MicroScope represents the lifetime of one or more resources. When a scope is closed, the resources associated with it are guaranteed to be released.

With the MicroScope data type, you can:

  • Add finalizers: A finalizer specifies the cleanup logic for a resource.
  • Close the scope: When the scope is closed, all resources are released, and the finalizers are executed.

Example (Managing a Scope)

import {
import Micro
Micro
} from "effect"
// Helper function to log a message
const
const log: (message: string) => Micro.Micro<void, never, never>
log
= (
message: string
message
: string) =>
import Micro
Micro
.
const sync: <void>(evaluate: LazyArg<void>) => Micro.Micro<void, never, never>

Creates a Micro effect that succeeds with a lazily evaluated value.

If the evaluation of the value throws an error, the effect will fail with a Die variant of the MicroCause type.

@since3.4.0

sync
(() =>
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
(
message: string
message
))
const
const program: Micro.Micro<void, never, never>
program
=
// create a new scope
import Micro
Micro
.
const scopeMake: Micro.Micro<Micro.MicroScope.Closeable, never, never>

@since3.4.0

scopeMake
.
Pipeable.pipe<Micro.Micro<Micro.MicroScope.Closeable, never, never>, Micro.Micro<Micro.MicroScope.Closeable, never, never>, Micro.Micro<Micro.MicroScope.Closeable, never, never>, Micro.Micro<...>>(this: Micro.Micro<...>, ab: (_: Micro.Micro<...>) => Micro.Micro<...>, bc: (_: Micro.Micro<...>) => Micro.Micro<...>, cd: (_: Micro.Micro<...>) => Micro.Micro<...>): Micro.Micro<...> (+21 overloads)
pipe
(
// add finalizer 1
import Micro
Micro
.
const tap: <Micro.MicroScope.Closeable, Micro.Micro<void, never, never>>(f: (a: NoInfer<Micro.MicroScope.Closeable>) => Micro.Micro<void, never, never>) => <E, R>(self: Micro.Micro<...>) => Micro.Micro<...> (+3 overloads)

Execute a side effect from the success value of the Micro effect.

It is similar to the andThen api, but the success value is ignored.

@since3.4.0

tap
((
scope: NoInfer<Micro.MicroScope.Closeable>
scope
) =>
scope: Micro.MicroScope.Closeable
scope
.
MicroScope.addFinalizer: (finalizer: (exit: Micro.MicroExit<unknown, unknown>) => Micro.Micro<void>) => Micro.Micro<void>
addFinalizer
(() =>
const log: (message: string) => Micro.Micro<void, never, never>
log
("finalizer 1"))),
// add finalizer 2
import Micro
Micro
.
const tap: <Micro.MicroScope.Closeable, Micro.Micro<void, never, never>>(f: (a: NoInfer<Micro.MicroScope.Closeable>) => Micro.Micro<void, never, never>) => <E, R>(self: Micro.Micro<...>) => Micro.Micro<...> (+3 overloads)

Execute a side effect from the success value of the Micro effect.

It is similar to the andThen api, but the success value is ignored.

@since3.4.0

tap
((
scope: NoInfer<Micro.MicroScope.Closeable>
scope
) =>
scope: Micro.MicroScope.Closeable
scope
.
MicroScope.addFinalizer: (finalizer: (exit: Micro.MicroExit<unknown, unknown>) => Micro.Micro<void>) => Micro.Micro<void>
addFinalizer
(() =>
const log: (message: string) => Micro.Micro<void, never, never>
log
("finalizer 2"))),
// close the scope
import Micro
Micro
.
const andThen: <Micro.MicroScope.Closeable, Micro.Micro<void, never, never>>(f: (a: Micro.MicroScope.Closeable) => Micro.Micro<void, never, never>) => <E, R>(self: Micro.Micro<...>) => Micro.Micro<...> (+3 overloads)

A more flexible version of flatMap that combines map and flatMap into a single API.

It also lets you directly pass a Micro effect, which will be executed after the current effect.

@since3.4.0

andThen
((
scope: Micro.MicroScope.Closeable
scope
) =>
scope: Micro.MicroScope.Closeable
scope
.
MicroScope.Closeable.close: (exit: Micro.MicroExit<any, any>) => Micro.Micro<void>
close
(
import Micro
Micro
.
const exitSucceed: <string>(a: string) => Micro.MicroExit<string, never>

@since3.4.6

exitSucceed
("scope closed successfully"))
)
)
import Micro
Micro
.
const runPromise: <void, never>(effect: Micro.Micro<void, never, never>, options?: {
readonly signal?: AbortSignal | undefined;
readonly scheduler?: Micro.MicroScheduler | undefined;
} | undefined) => Promise<...>

Execute the Micro effect and return a Promise that resolves with the successful value of the computation.

@since3.4.0

runPromise
(
const program: Micro.Micro<void, never, never>
program
)
/*
Output:
finalizer 2 <-- finalizers are closed in reverse order
finalizer 1
*/

In the above example, finalizers are added to the scope, and when the scope is closed, the finalizers are executed in the reverse order.

This reverse order is important because it ensures that resources are released in the correct sequence.

For instance, if you acquire a network connection and then access a file on a remote server, the file must be closed before the network connection to avoid errors.

The Micro.addFinalizer function is a high-level API that allows you to add finalizers to the scope of an effect. A finalizer is a piece of code that is guaranteed to run when the associated scope is closed. The behavior of the finalizer can vary based on the MicroExit value, which represents how the scope was closed—whether successfully or with an error.

Example (Adding a Finalizer on Success)

import {
import Micro
Micro
} from "effect"
// Helper function to log a message
const
const log: (message: string) => Micro.Micro<void, never, never>
log
= (
message: string
message
: string) =>
import Micro
Micro
.
const sync: <void>(evaluate: LazyArg<void>) => Micro.Micro<void, never, never>

Creates a Micro effect that succeeds with a lazily evaluated value.

If the evaluation of the value throws an error, the effect will fail with a Die variant of the MicroCause type.

@since3.4.0

sync
(() =>
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
(
message: string
message
))
// ┌─── Micro<string, never, MicroScope>
// ▼
const
const program: Micro.Micro<string, never, Micro.MicroScope>
program
=
import Micro
Micro
.
const gen: <unknown, YieldWrap<Micro.Micro<void, never, Micro.MicroScope>>, string>(...args: [self: unknown, body: (this: unknown) => Generator<YieldWrap<Micro.Micro<void, never, Micro.MicroScope>>, string, never>] | [body: ...]) => Micro.Micro<...>

@since3.4.0

gen
(function* () {
yield*
import Micro
Micro
.
const addFinalizer: (finalizer: (exit: Micro.MicroExit<unknown, unknown>) => Micro.Micro<void>) => Micro.Micro<void, never, Micro.MicroScope>

Add a finalizer to the current MicroScope.

@since3.4.0

addFinalizer
((
exit: Micro.MicroExit<unknown, unknown>
exit
) =>
const log: (message: string) => Micro.Micro<void, never, never>
log
(`finalizer after ${
exit: Micro.MicroExit<unknown, unknown>
exit
.
_tag: "Success" | "Failure"
_tag
}`))
return "some result"
})
// ┌─── Micro<string, never, never>
// ▼
const
const runnable: Micro.Micro<string, never, never>
runnable
=
import Micro
Micro
.
const scoped: <string, never, Micro.MicroScope>(self: Micro.Micro<string, never, Micro.MicroScope>) => Micro.Micro<string, never, never>

Provide a MicroScope to the given effect, closing it after the effect has finished executing.

@since3.4.0

scoped
(
const program: Micro.Micro<string, never, Micro.MicroScope>
program
)
import Micro
Micro
.
const runPromise: <string, never>(effect: Micro.Micro<string, never, never>, options?: {
readonly signal?: AbortSignal | undefined;
readonly scheduler?: Micro.MicroScheduler | undefined;
} | undefined) => Promise<...>

Execute the Micro effect and return a Promise that resolves with the successful value of the computation.

@since3.4.0

runPromise
(
const runnable: Micro.Micro<string, never, never>
runnable
).
Promise<string>.then<void, void>(onfulfilled?: ((value: string) => void | PromiseLike<void>) | null | undefined, onrejected?: ((reason: any) => void | PromiseLike<void>) | 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
,
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.error(message?: any, ...optionalParams: any[]): void

Prints to stderr 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 code = 5;
console.error('error #%d', code);
// Prints: error #5, to stderr
console.error('error', code);
// Prints: error 5, to stderr

If formatting elements (e.g. %d) are not found in the first string then util.inspect() is called on each argument and the resulting string values are concatenated. See util.format() for more information.

@sincev0.1.100

error
)
/*
Output:
finalizer after Success
some result
*/

Next, let’s explore how things behave in the event of a failure:

Example (Adding a Finalizer on Failure)

import {
import Micro
Micro
} from "effect"
// Helper function to log a message
const
const log: (message: string) => Micro.Micro<void, never, never>
log
= (
message: string
message
: string) =>
import Micro
Micro
.
const sync: <void>(evaluate: LazyArg<void>) => Micro.Micro<void, never, never>

Creates a Micro effect that succeeds with a lazily evaluated value.

If the evaluation of the value throws an error, the effect will fail with a Die variant of the MicroCause type.

@since3.4.0

sync
(() =>
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
(
message: string
message
))
const
const program: Micro.Micro<never, string, Micro.MicroScope>
program
=
import Micro
Micro
.
const gen: <unknown, YieldWrap<Micro.Micro<never, string, never>> | YieldWrap<Micro.Micro<void, never, Micro.MicroScope>>, never>(...args: [self: unknown, body: (this: unknown) => Generator<...>] | [body: ...]) => Micro.Micro<...>

@since3.4.0

gen
(function* () {
yield*
import Micro
Micro
.
const addFinalizer: (finalizer: (exit: Micro.MicroExit<unknown, unknown>) => Micro.Micro<void>) => Micro.Micro<void, never, Micro.MicroScope>

Add a finalizer to the current MicroScope.

@since3.4.0

addFinalizer
((
exit: Micro.MicroExit<unknown, unknown>
exit
) =>
const log: (message: string) => Micro.Micro<void, never, never>
log
(`finalizer after ${
exit: Micro.MicroExit<unknown, unknown>
exit
.
_tag: "Success" | "Failure"
_tag
}`))
return yield*
import Micro
Micro
.
const fail: <string>(error: string) => Micro.Micro<never, string, never>

Creates a Micro effect that fails with the given error.

This results in a Fail variant of the MicroCause type, where the error is tracked at the type level.

@since3.4.0

fail
("Uh oh!")
})
const
const runnable: Micro.Micro<never, string, never>
runnable
=
import Micro
Micro
.
const scoped: <never, string, Micro.MicroScope>(self: Micro.Micro<never, string, Micro.MicroScope>) => Micro.Micro<never, string, never>

Provide a MicroScope to the given effect, closing it after the effect has finished executing.

@since3.4.0

scoped
(
const program: Micro.Micro<never, string, Micro.MicroScope>
program
)
import Micro
Micro
.
const runPromiseExit: <never, string>(effect: Micro.Micro<never, string, never>, options?: {
readonly signal?: AbortSignal | undefined;
readonly scheduler?: Micro.MicroScheduler | undefined;
} | undefined) => Promise<...>

Execute the Micro effect and return a Promise that resolves with the MicroExit of the computation.

@since3.4.6

runPromiseExit
(
const runnable: Micro.Micro<never, string, never>
runnable
).
Promise<MicroExit<never, string>>.then<void, never>(onfulfilled?: ((value: Micro.MicroExit<never, 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:
finalizer after Failure
{
"_id": "MicroExit",
"_tag": "Failure",
"cause": {
"_tag": "Fail",
"traces": [],
"name": "MicroCause.Fail",
"error": "Uh oh!"
}
}
*/

We can define a resource using operators like Micro.acquireRelease(acquire, release), which allows us to create a scoped value from an acquire and release workflow.

Every acquire release requires three actions:

  • Acquiring Resource. An effect describing the acquisition of resource. For example, opening a file.
  • Using Resource. An effect describing the actual process to produce a result. For example, counting the number of lines in a file.
  • Releasing Resource. An effect describing the final step of releasing or cleaning up the resource. For example, closing a file.

The Micro.acquireRelease operator performs the acquire workflow uninterruptibly. This is important because if we allowed interruption during resource acquisition we could be interrupted when the resource was partially acquired.

The guarantee of the Micro.acquireRelease operator is that if the acquire workflow successfully completes execution then the release workflow is guaranteed to be run when the Scope is closed.

Example (Defining a Simple Resource)

import {
import Micro
Micro
} from "effect"
// Define an interface for a resource
interface
interface MyResource
MyResource
{
readonly
MyResource.contents: string
contents
: string
readonly
MyResource.close: () => Promise<void>
close
: () =>
interface Promise<T>

Represents the completion of an asynchronous operation

Promise
<void>
}
// Simulate resource acquisition
const
const getMyResource: () => Promise<MyResource>
getMyResource
= ():
interface Promise<T>

Represents the completion of an asynchronous operation

Promise
<
interface MyResource
MyResource
> =>
var Promise: PromiseConstructor

Represents the completion of an asynchronous operation

Promise
.
PromiseConstructor.resolve<{
contents: string;
close: () => Promise<void>;
}>(value: {
contents: string;
close: () => Promise<void>;
}): Promise<{
contents: string;
close: () => Promise<void>;
}> (+2 overloads)

Creates a new resolved promise for the provided value.

@paramvalue A promise.

@returnsA promise whose internal state matches the provided promise.

resolve
({
contents: string
contents
: "lorem ipsum",
close: () => Promise<void>
close
: () =>
new
var Promise: PromiseConstructor
new <void>(executor: (resolve: (value: void | PromiseLike<void>) => void, reject: (reason?: any) => void) => void) => Promise<void>

Creates a new Promise.

@paramexecutor A callback used to initialize the promise. This callback is passed two arguments: a resolve callback used to resolve the promise with a value or the result of another promise, and a reject callback used to reject the promise with a provided reason or error.

Promise
((
resolve: (value: void | PromiseLike<void>) => void
resolve
) => {
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
("Resource released")
resolve: (value: void | PromiseLike<void>) => void
resolve
()
})
})
// Define how the resource is acquired
const
const acquire: Micro.Micro<MyResource, Error, never>
acquire
=
import Micro
Micro
.
const tryPromise: <MyResource, Error>(options: {
readonly try: (signal: AbortSignal) => PromiseLike<MyResource>;
readonly catch: (error: unknown) => Error;
}) => Micro.Micro<...>

Wrap a Promise into a Micro effect. Any errors will be caught and converted into a specific error type.

@example

import { Micro } from "effect"
Micro.tryPromise({
try: () => Promise.resolve("success"),
catch: (cause) => new Error("caught", { cause })
})

@since3.4.0

tryPromise
({
try: (signal: AbortSignal) => PromiseLike<MyResource>
try
: () =>
const getMyResource: () => Promise<MyResource>
getMyResource
().
Promise<MyResource>.then<MyResource, never>(onfulfilled?: ((value: MyResource) => MyResource | PromiseLike<MyResource>) | null | undefined, onrejected?: ((reason: any) => PromiseLike<...>) | ... 1 more ... | 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
((
res: MyResource
res
) => {
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
("Resource acquired")
return
res: MyResource
res
}),
catch: (error: unknown) => Error
catch
: () => new
var Error: ErrorConstructor
new (message?: string) => Error
Error
("getMyResourceError")
})
// Define how the resource is released
const
const release: (res: MyResource) => Micro.Micro<void, never, never>
release
= (
res: MyResource
res
:
interface MyResource
MyResource
) =>
import Micro
Micro
.
const promise: <void>(evaluate: (signal: AbortSignal) => PromiseLike<void>) => Micro.Micro<void, never, never>

Wrap a Promise into a Micro effect.

Any errors will result in a Die variant of the MicroCause type, where the error is not tracked at the type level.

@since3.4.0

promise
(() =>
res: MyResource
res
.
MyResource.close: () => Promise<void>
close
())
// Create the resource management workflow
//
// ┌─── Micro<MyResource, Error, MicroScope>
// ▼
const
const resource: Micro.Micro<MyResource, Error, Micro.MicroScope>
resource
=
import Micro
Micro
.
const acquireRelease: <MyResource, Error, never>(acquire: Micro.Micro<MyResource, Error, never>, release: (a: MyResource, exit: Micro.MicroExit<unknown, unknown>) => Micro.Micro<void>) => Micro.Micro<...>

Create a resource with a cleanup Micro effect, ensuring the cleanup is executed when the MicroScope is closed.

@since3.4.0

acquireRelease
(
const acquire: Micro.Micro<MyResource, Error, never>
acquire
,
const release: (res: MyResource) => Micro.Micro<void, never, never>
release
)
// ┌─── Micro<void, Error, never>
// ▼
const
const program: Micro.Micro<void, Error, never>
program
=
import Micro
Micro
.
const scoped: <void, Error, Micro.MicroScope>(self: Micro.Micro<void, Error, Micro.MicroScope>) => Micro.Micro<void, Error, never>

Provide a MicroScope to the given effect, closing it after the effect has finished executing.

@since3.4.0

scoped
(
import Micro
Micro
.
const gen: <unknown, YieldWrap<Micro.Micro<MyResource, Error, Micro.MicroScope>>, void>(...args: [self: unknown, body: (this: unknown) => Generator<YieldWrap<Micro.Micro<MyResource, Error, Micro.MicroScope>>, void, never>] | [body: ...]) => Micro.Micro<...>

@since3.4.0

gen
(function* () {
const
const res: MyResource
res
= yield*
const resource: Micro.Micro<MyResource, Error, Micro.MicroScope>
resource
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
(`content is ${
const res: MyResource
res
.
MyResource.contents: string
contents
}`)
})
)
import Micro
Micro
.
const runPromise: <void, Error>(effect: Micro.Micro<void, Error, never>, options?: {
readonly signal?: AbortSignal | undefined;
readonly scheduler?: Micro.MicroScheduler | undefined;
} | undefined) => Promise<...>

Execute the Micro effect and return a Promise that resolves with the successful value of the computation.

@since3.4.0

runPromise
(
const program: Micro.Micro<void, Error, never>
program
)
/*
Resource acquired
content is lorem ipsum
Resource released
*/

The Micro.scoped operator removes the MicroScope from the context, indicating that there are no longer any resources used by this workflow which require a scope.

The Micro.acquireUseRelease(acquire, use, release) function is a specialized version of the Micro.acquireRelease function that simplifies resource management by automatically handling the scoping of resources.

The main difference is that acquireUseRelease eliminates the need to manually call Micro.scoped to manage the resource’s scope. It has additional knowledge about when you are done using the resource created with the acquire step. This is achieved by providing a use argument, which represents the function that operates on the acquired resource. As a result, acquireUseRelease can automatically determine when it should execute the release step.

Example (Automatically Managing Resource Lifetime)

import {
import Micro
Micro
} from "effect"
// Define the interface for the resource
interface
interface MyResource
MyResource
{
readonly
MyResource.contents: string
contents
: string
readonly
MyResource.close: () => Promise<void>
close
: () =>
interface Promise<T>

Represents the completion of an asynchronous operation

Promise
<void>
}
// Simulate getting the resource
const
const getMyResource: () => Promise<MyResource>
getMyResource
= ():
interface Promise<T>

Represents the completion of an asynchronous operation

Promise
<
interface MyResource
MyResource
> =>
var Promise: PromiseConstructor

Represents the completion of an asynchronous operation

Promise
.
PromiseConstructor.resolve<{
contents: string;
close: () => Promise<void>;
}>(value: {
contents: string;
close: () => Promise<void>;
}): Promise<{
contents: string;
close: () => Promise<void>;
}> (+2 overloads)

Creates a new resolved promise for the provided value.

@paramvalue A promise.

@returnsA promise whose internal state matches the provided promise.

resolve
({
contents: string
contents
: "lorem ipsum",
close: () => Promise<void>
close
: () =>
new
var Promise: PromiseConstructor
new <void>(executor: (resolve: (value: void | PromiseLike<void>) => void, reject: (reason?: any) => void) => void) => Promise<void>

Creates a new Promise.

@paramexecutor A callback used to initialize the promise. This callback is passed two arguments: a resolve callback used to resolve the promise with a value or the result of another promise, and a reject callback used to reject the promise with a provided reason or error.

Promise
((
resolve: (value: void | PromiseLike<void>) => void
resolve
) => {
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
("Resource released")
resolve: (value: void | PromiseLike<void>) => void
resolve
()
})
})
// Define the acquisition of the resource with error handling
const
const acquire: Micro.Micro<MyResource, Error, never>
acquire
=
import Micro
Micro
.
const tryPromise: <MyResource, Error>(options: {
readonly try: (signal: AbortSignal) => PromiseLike<MyResource>;
readonly catch: (error: unknown) => Error;
}) => Micro.Micro<...>

Wrap a Promise into a Micro effect. Any errors will be caught and converted into a specific error type.

@example

import { Micro } from "effect"
Micro.tryPromise({
try: () => Promise.resolve("success"),
catch: (cause) => new Error("caught", { cause })
})

@since3.4.0

tryPromise
({
try: (signal: AbortSignal) => PromiseLike<MyResource>
try
: () =>
const getMyResource: () => Promise<MyResource>
getMyResource
().
Promise<MyResource>.then<MyResource, never>(onfulfilled?: ((value: MyResource) => MyResource | PromiseLike<MyResource>) | null | undefined, onrejected?: ((reason: any) => PromiseLike<...>) | ... 1 more ... | 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
((
res: MyResource
res
) => {
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
("Resource acquired")
return
res: MyResource
res
}),
catch: (error: unknown) => Error
catch
: () => new
var Error: ErrorConstructor
new (message?: string) => Error
Error
("getMyResourceError")
})
// Define the release of the resource
const
const release: (res: MyResource) => Micro.Micro<void, never, never>
release
= (
res: MyResource
res
:
interface MyResource
MyResource
) =>
import Micro
Micro
.
const promise: <void>(evaluate: (signal: AbortSignal) => PromiseLike<void>) => Micro.Micro<void, never, never>

Wrap a Promise into a Micro effect.

Any errors will result in a Die variant of the MicroCause type, where the error is not tracked at the type level.

@since3.4.0

promise
(() =>
res: MyResource
res
.
MyResource.close: () => Promise<void>
close
())
const
const use: (res: MyResource) => Micro.Micro<void, never, never>
use
= (
res: MyResource
res
:
interface MyResource
MyResource
) =>
import Micro
Micro
.
const sync: <void>(evaluate: LazyArg<void>) => Micro.Micro<void, never, never>

Creates a Micro effect that succeeds with a lazily evaluated value.

If the evaluation of the value throws an error, the effect will fail with a Die variant of the MicroCause type.

@since3.4.0

sync
(() =>
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
(`content is ${
res: MyResource
res
.
MyResource.contents: string
contents
}`))
// ┌─── Micro<void, Error, never>
// ▼
const
const program: Micro.Micro<void, Error, never>
program
=
import Micro
Micro
.
const acquireUseRelease: <MyResource, Error, never, void, never, never, never, never>(acquire: Micro.Micro<MyResource, Error, never>, use: (a: MyResource) => Micro.Micro<...>, release: (a: MyResource, exit: Micro.MicroExit<...>) => Micro.Micro<...>) => Micro.Micro<...>

Acquire a resource, use it, and then release the resource when the use effect has completed.

@since3.4.0

acquireUseRelease
(
const acquire: Micro.Micro<MyResource, Error, never>
acquire
,
const use: (res: MyResource) => Micro.Micro<void, never, never>
use
,
const release: (res: MyResource) => Micro.Micro<void, never, never>
release
)
import Micro
Micro
.
const runPromise: <void, Error>(effect: Micro.Micro<void, Error, never>, options?: {
readonly signal?: AbortSignal | undefined;
readonly scheduler?: Micro.MicroScheduler | undefined;
} | undefined) => Promise<...>

Execute the Micro effect and return a Promise that resolves with the successful value of the computation.

@since3.4.0

runPromise
(
const program: Micro.Micro<void, Error, never>
program
)
/*
Resource acquired
content is lorem ipsum
Resource released
*/

The MicroSchedule type represents a function that can be used to calculate the delay between repeats.

type MicroSchedule = (attempt: number, elapsed: number) => Option<number>

The function takes the current attempt number and the elapsed time since the first attempt, and returns the delay for the next attempt. If the function returns None, the repetition will stop.

The Micro.repeat function returns a new effect that repeats the given effect according to a specified schedule or until the first failure.

Example (Repeating a Successful Effect)

import {
import Micro
Micro
} from "effect"
// Define an effect that logs a message to the console
const
const action: Micro.Micro<void, never, never>
action
=
import Micro
Micro
.
const sync: <void>(evaluate: LazyArg<void>) => Micro.Micro<void, never, never>

Creates a Micro effect that succeeds with a lazily evaluated value.

If the evaluation of the value throws an error, the effect will fail with a Die variant of the MicroCause type.

@since3.4.0

sync
(() =>
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
("success"))
// Define a schedule that repeats the action 2 more times with a delay
const
const policy: Micro.MicroSchedule
policy
=
import Micro
Micro
.
const scheduleAddDelay: (self: Micro.MicroSchedule, f: () => number) => Micro.MicroSchedule (+1 overload)

Returns a new MicroSchedule with an added calculated delay to each delay returned by this schedule.

@since3.4.6

scheduleAddDelay
(
import Micro
Micro
.
const scheduleRecurs: (n: number) => Micro.MicroSchedule

Create a MicroSchedule that will stop repeating after the specified number of attempts.

@since3.4.6

scheduleRecurs
(2), () => 100)
// Repeat the action according to the schedule
const
const program: Micro.Micro<void, never, never>
program
=
import Micro
Micro
.
const repeat: <void, never, never>(self: Micro.Micro<void, never, never>, options?: {
while?: Predicate<void> | undefined;
times?: number | undefined;
schedule?: Micro.MicroSchedule | undefined;
} | undefined) => Micro.Micro<...> (+1 overload)

Repeat the given Micro effect using the provided options. Only successful results will be repeated.

@since3.4.0

repeat
(
const action: Micro.Micro<void, never, never>
action
, {
schedule?: Micro.MicroSchedule | undefined
schedule
:
const policy: Micro.MicroSchedule
policy
})
import Micro
Micro
.
const runPromise: <void, never>(effect: Micro.Micro<void, never, never>, options?: {
readonly signal?: AbortSignal | undefined;
readonly scheduler?: Micro.MicroScheduler | undefined;
} | undefined) => Promise<...>

Execute the Micro effect and return a Promise that resolves with the successful value of the computation.

@since3.4.0

runPromise
(
const program: Micro.Micro<void, never, never>
program
)
/*
Output:
success
success
success
*/

Example (Handling Failures in Repetition)

import {
import Micro
Micro
} from "effect"
let
let count: number
count
= 0
// Define an async effect that simulates an action with potential failure
const
const action: Micro.Micro<string, string, never>
action
=
import Micro
Micro
.
const async: <string, string, never>(register: (resume: (effect: Micro.Micro<string, string, never>) => void, signal: AbortSignal) => void | Micro.Micro<void, never, never>) => Micro.Micro<...>

Create a Micro effect from an asynchronous computation.

You can return a cleanup effect that will be run when the effect is aborted. It is also passed an AbortSignal that is triggered when the effect is aborted.

@since3.4.0

async
<string, string>((
resume: (effect: Micro.Micro<string, string, never>) => void
resume
) => {
if (
let count: number
count
> 1) {
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
("failure")
resume: (effect: Micro.Micro<string, string, never>) => void
resume
(
import Micro
Micro
.
const fail: <string>(error: string) => Micro.Micro<never, string, never>

Creates a Micro effect that fails with the given error.

This results in a Fail variant of the MicroCause type, where the error is tracked at the type level.

@since3.4.0

fail
("Uh oh!"))
} else {
let count: number
count
++
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
("success")
resume: (effect: Micro.Micro<string, string, never>) => void
resume
(
import Micro
Micro
.
const succeed: <string>(value: string) => Micro.Micro<string, never, never>

Creates a Micro effect that will succeed with the specified constant value.

@since3.4.0

succeed
("yay!"))
}
})
// Define a schedule that repeats the action 2 more times with a delay
const
const policy: Micro.MicroSchedule
policy
=
import Micro
Micro
.
const scheduleAddDelay: (self: Micro.MicroSchedule, f: () => number) => Micro.MicroSchedule (+1 overload)

Returns a new MicroSchedule with an added calculated delay to each delay returned by this schedule.

@since3.4.6

scheduleAddDelay
(
import Micro
Micro
.
const scheduleRecurs: (n: number) => Micro.MicroSchedule

Create a MicroSchedule that will stop repeating after the specified number of attempts.

@since3.4.6

scheduleRecurs
(2), () => 100)
// Repeat the action according to the schedule
const
const program: Micro.Micro<string, string, never>
program
=
import Micro
Micro
.
const repeat: <string, string, never>(self: Micro.Micro<string, string, never>, options?: {
while?: Predicate<string> | undefined;
times?: number | undefined;
schedule?: Micro.MicroSchedule | undefined;
} | undefined) => Micro.Micro<...> (+1 overload)

Repeat the given Micro effect using the provided options. Only successful results will be repeated.

@since3.4.0

repeat
(
const action: Micro.Micro<string, string, never>
action
, {
schedule?: Micro.MicroSchedule | undefined
schedule
:
const policy: Micro.MicroSchedule
policy
})
// Run the program and observe the result on failure
import Micro
Micro
.
const runPromiseExit: <string, string>(effect: Micro.Micro<string, string, never>, options?: {
readonly signal?: AbortSignal | undefined;
readonly scheduler?: Micro.MicroScheduler | undefined;
} | undefined) => Promise<...>

Execute the Micro effect and return a Promise that resolves with the MicroExit of the computation.

@since3.4.6

runPromiseExit
(
const program: Micro.Micro<string, string, never>
program
).
Promise<MicroExit<string, string>>.then<void, never>(onfulfilled?: ((value: Micro.MicroExit<string, string>) => void | PromiseLike<void>) | null | undefined, onrejected?: ((reason: any) => PromiseLike<never>) | null | undefined): Promise<...>

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

@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:
success
success
failure
{
"_id": "MicroExit",
"_tag": "Failure",
"cause": {
"_tag": "Fail",
"traces": [],
"name": "MicroCause.Fail",
"error": "Uh oh!"
}
}
*/

This helper function, dryRun, demonstrates how different scheduling policies control repetition timing without executing an actual effect. By returning an array of delay intervals, it visualizes how a schedule would space repetitions.

import {
import Option

@since2.0.0

@since2.0.0

Option
,
import Micro
Micro
} from "effect"
// Helper function to simulate and visualize a schedule's behavior
const
const dryRun: (schedule: Micro.MicroSchedule, maxAttempt?: number) => Array<number>
dryRun
= (
schedule: Micro.MicroSchedule
schedule
:
import Micro
Micro
.
type MicroSchedule = (attempt: number, elapsed: number) => Option.Option<number>

The MicroSchedule type represents a function that can be used to calculate the delay between repeats.

The function takes the current attempt number and the elapsed time since the first attempt, and returns the delay for the next attempt. If the function returns None, the repetition will stop.

@since3.4.6

MicroSchedule
, // The scheduling policy to simulate
maxAttempt: number
maxAttempt
: number = 7 // Maximum number of repetitions to simulate
):
interface Array<T>
Array
<number> => {
let
let attempt: number
attempt
= 1 // Track the current attempt number
let
let elapsed: number
elapsed
= 0 // Track the total elapsed time
const
const out: number[]
out
:
interface Array<T>
Array
<number> = [] // Array to store each delay duration
let
let duration: Option.Option<number>
duration
=
schedule: (attempt: number, elapsed: number) => Option.Option<number>
schedule
(
let attempt: number
attempt
,
let elapsed: number
elapsed
)
// Continue until the schedule returns no delay or maxAttempt is reached
while (
import Option

@since2.0.0

@since2.0.0

Option
.
const isSome: <number>(self: Option.Option<number>) => self is Option.Some<number>

Determine if a Option is a Some.

@paramself - The Option to check.

@example

import { Option } from "effect"
assert.deepStrictEqual(Option.isSome(Option.some(1)), true)
assert.deepStrictEqual(Option.isSome(Option.none()), false)

@since2.0.0

isSome
(
let duration: Option.Option<number>
duration
) &&
let attempt: number
attempt
<=
maxAttempt: number
maxAttempt
) {
const
const value: number
value
=
let duration: Option.Some<number>
duration
.
Some<number>.value: number
value
const out: number[]
out
.
Array<number>.push(...items: number[]): number

Appends new elements to the end of an array, and returns the new length of the array.

@paramitems New elements to add to the array.

push
(
const value: number
value
)
let attempt: number
attempt
++
let elapsed: number
elapsed
+=
const value: number
value
// Get the next duration based on the current attempt
// and total elapsed time
let duration: Option.Option<number>
duration
=
schedule: (attempt: number, elapsed: number) => Option.Option<number>
schedule
(
let attempt: number
attempt
,
let elapsed: number
elapsed
)
}
return
const out: number[]
out
}

A schedule that repeats indefinitely, each repetition spaced the specified duration from the last run.

Example (Recurring with Delay Between Executions)

import {
import Micro
Micro
} from "effect"
import * as
import Option

@since2.0.0

@since2.0.0

Option
from "effect/Option"
// Helper function to simulate and visualize a schedule's behavior
17 collapsed lines
const
const dryRun: (schedule: Micro.MicroSchedule, maxAttempt?: number) => Array<number>
dryRun
= (
schedule: Micro.MicroSchedule
schedule
:
import Micro
Micro
.
type MicroSchedule = (attempt: number, elapsed: number) => Option.Option<number>

The MicroSchedule type represents a function that can be used to calculate the delay between repeats.

The function takes the current attempt number and the elapsed time since the first attempt, and returns the delay for the next attempt. If the function returns None, the repetition will stop.

@since3.4.6

MicroSchedule
,
maxAttempt: number
maxAttempt
: number = 7
):
interface Array<T>
Array
<number> => {
let
let attempt: number
attempt
= 1
let
let elapsed: number
elapsed
= 0
const
const out: number[]
out
:
interface Array<T>
Array
<number> = []
let
let duration: Option.Option<number>
duration
=
schedule: (attempt: number, elapsed: number) => Option.Option<number>
schedule
(
let attempt: number
attempt
,
let elapsed: number
elapsed
)
while (
import Option

@since2.0.0

@since2.0.0

Option
.
const isSome: <number>(self: Option.Option<number>) => self is Option.Some<number>

Determine if a Option is a Some.

@paramself - The Option to check.

@example

import { Option } from "effect"
assert.deepStrictEqual(Option.isSome(Option.some(1)), true)
assert.deepStrictEqual(Option.isSome(Option.none()), false)

@since2.0.0

isSome
(
let duration: Option.Option<number>
duration
) &&
let attempt: number
attempt
<=
maxAttempt: number
maxAttempt
) {
const
const value: number
value
=
let duration: Option.Some<number>
duration
.
Some<number>.value: number
value
let attempt: number
attempt
++
let elapsed: number
elapsed
+=
const value: number
value
const out: number[]
out
.
Array<number>.push(...items: number[]): number

Appends new elements to the end of an array, and returns the new length of the array.

@paramitems New elements to add to the array.

push
(
const value: number
value
)
let duration: Option.Option<number>
duration
=
schedule: (attempt: number, elapsed: number) => Option.Option<number>
schedule
(
let attempt: number
attempt
,
let elapsed: number
elapsed
)
}
return
const out: number[]
out
}
const
const policy: Micro.MicroSchedule
policy
=
import Micro
Micro
.
const scheduleSpaced: (millis: number) => Micro.MicroSchedule

Create a MicroSchedule that will generate a constant delay.

@since3.4.6

scheduleSpaced
(10)
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
(
const dryRun: (schedule: Micro.MicroSchedule, maxAttempt?: number) => Array<number>
dryRun
(
const policy: Micro.MicroSchedule
policy
))
/*
Output:
[
10, 10, 10, 10,
10, 10, 10
]
*/

A schedule that recurs using exponential backoff, with each delay increasing exponentially.

Example (Exponential Backoff Schedule)

import {
import Micro
Micro
} from "effect"
import * as
import Option

@since2.0.0

@since2.0.0

Option
from "effect/Option"
// Helper function to simulate and visualize a schedule's behavior
17 collapsed lines
const
const dryRun: (schedule: Micro.MicroSchedule, maxAttempt?: number) => Array<number>
dryRun
= (
schedule: Micro.MicroSchedule
schedule
:
import Micro
Micro
.
type MicroSchedule = (attempt: number, elapsed: number) => Option.Option<number>

The MicroSchedule type represents a function that can be used to calculate the delay between repeats.

The function takes the current attempt number and the elapsed time since the first attempt, and returns the delay for the next attempt. If the function returns None, the repetition will stop.

@since3.4.6

MicroSchedule
,
maxAttempt: number
maxAttempt
: number = 7
):
interface Array<T>
Array
<number> => {
let
let attempt: number
attempt
= 1
let
let elapsed: number
elapsed
= 0
const
const out: number[]
out
:
interface Array<T>
Array
<number> = []
let
let duration: Option.Option<number>
duration
=
schedule: (attempt: number, elapsed: number) => Option.Option<number>
schedule
(
let attempt: number
attempt
,
let elapsed: number
elapsed
)
while (
import Option

@since2.0.0

@since2.0.0

Option
.
const isSome: <number>(self: Option.Option<number>) => self is Option.Some<number>

Determine if a Option is a Some.

@paramself - The Option to check.

@example

import { Option } from "effect"
assert.deepStrictEqual(Option.isSome(Option.some(1)), true)
assert.deepStrictEqual(Option.isSome(Option.none()), false)

@since2.0.0

isSome
(
let duration: Option.Option<number>
duration
) &&
let attempt: number
attempt
<=
maxAttempt: number
maxAttempt
) {
const
const value: number
value
=
let duration: Option.Some<number>
duration
.
Some<number>.value: number
value
let attempt: number
attempt
++
let elapsed: number
elapsed
+=
const value: number
value
const out: number[]
out
.
Array<number>.push(...items: number[]): number

Appends new elements to the end of an array, and returns the new length of the array.

@paramitems New elements to add to the array.

push
(
const value: number
value
)
let duration: Option.Option<number>
duration
=
schedule: (attempt: number, elapsed: number) => Option.Option<number>
schedule
(
let attempt: number
attempt
,
let elapsed: number
elapsed
)
}
return
const out: number[]
out
}
const
const policy: Micro.MicroSchedule
policy
=
import Micro
Micro
.
const scheduleExponential: (baseMillis: number, factor?: number) => Micro.MicroSchedule

Create a MicroSchedule that will generate a delay with an exponential backoff.

@since3.4.6

scheduleExponential
(10)
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
(
const dryRun: (schedule: Micro.MicroSchedule, maxAttempt?: number) => Array<number>
dryRun
(
const policy: Micro.MicroSchedule
policy
))
/*
Output:
[
20, 40, 80,
160, 320, 640,
1280
]
*/

Combines two schedules using union. The schedule recurs as long as one of the schedules wants to, using the minimum delay between recurrences.

Example (Union of Exponential and Spaced Schedules)

import {
import Micro
Micro
} from "effect"
import * as
import Option

@since2.0.0

@since2.0.0

Option
from "effect/Option"
// Helper function to simulate and visualize a schedule's behavior
17 collapsed lines
const
const dryRun: (schedule: Micro.MicroSchedule, maxAttempt?: number) => Array<number>
dryRun
= (
schedule: Micro.MicroSchedule
schedule
:
import Micro
Micro
.
type MicroSchedule = (attempt: number, elapsed: number) => Option.Option<number>

The MicroSchedule type represents a function that can be used to calculate the delay between repeats.

The function takes the current attempt number and the elapsed time since the first attempt, and returns the delay for the next attempt. If the function returns None, the repetition will stop.

@since3.4.6

MicroSchedule
,
maxAttempt: number
maxAttempt
: number = 7
):
interface Array<T>
Array
<number> => {
let
let attempt: number
attempt
= 1
let
let elapsed: number
elapsed
= 0
const
const out: number[]
out
:
interface Array<T>
Array
<number> = []
let
let duration: Option.Option<number>
duration
=
schedule: (attempt: number, elapsed: number) => Option.Option<number>
schedule
(
let attempt: number
attempt
,
let elapsed: number
elapsed
)
while (
import Option

@since2.0.0

@since2.0.0

Option
.
const isSome: <number>(self: Option.Option<number>) => self is Option.Some<number>

Determine if a Option is a Some.

@paramself - The Option to check.

@example

import { Option } from "effect"
assert.deepStrictEqual(Option.isSome(Option.some(1)), true)
assert.deepStrictEqual(Option.isSome(Option.none()), false)

@since2.0.0

isSome
(
let duration: Option.Option<number>
duration
) &&
let attempt: number
attempt
<=
maxAttempt: number
maxAttempt
) {
const
const value: number
value
=
let duration: Option.Some<number>
duration
.
Some<number>.value: number
value
let attempt: number
attempt
++
let elapsed: number
elapsed
+=
const value: number
value
const out: number[]
out
.
Array<number>.push(...items: number[]): number

Appends new elements to the end of an array, and returns the new length of the array.

@paramitems New elements to add to the array.

push
(
const value: number
value
)
let duration: Option.Option<number>
duration
=
schedule: (attempt: number, elapsed: number) => Option.Option<number>
schedule
(
let attempt: number
attempt
,
let elapsed: number
elapsed
)
}
return
const out: number[]
out
}
const
const policy: Micro.MicroSchedule
policy
=
import Micro
Micro
.
const scheduleUnion: (self: Micro.MicroSchedule, that: Micro.MicroSchedule) => Micro.MicroSchedule (+1 overload)

Combines two MicroSchedules, by recurring if either schedule wants to recur, using the minimum of the two durations between recurrences.

@since3.4.6

scheduleUnion
(
import Micro
Micro
.
const scheduleExponential: (baseMillis: number, factor?: number) => Micro.MicroSchedule

Create a MicroSchedule that will generate a delay with an exponential backoff.

@since3.4.6

scheduleExponential
(10),
import Micro
Micro
.
const scheduleSpaced: (millis: number) => Micro.MicroSchedule

Create a MicroSchedule that will generate a constant delay.

@since3.4.6

scheduleSpaced
(300)
)
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
(
const dryRun: (schedule: Micro.MicroSchedule, maxAttempt?: number) => Array<number>
dryRun
(
const policy: Micro.MicroSchedule
policy
))
/*
Output:
[
20, < exponential
40,
80,
160,
300, < spaced
300,
300
]
*/

Combines two schedules using intersection. The schedule recurs only if both schedules want to continue, using the maximum delay between them.

Example (Intersection of Exponential and Recurs Schedules)

import {
import Micro
Micro
} from "effect"
import * as
import Option

@since2.0.0

@since2.0.0

Option
from "effect/Option"
// Helper function to simulate and visualize a schedule's behavior
17 collapsed lines
const
const dryRun: (schedule: Micro.MicroSchedule, maxAttempt?: number) => Array<number>
dryRun
= (
schedule: Micro.MicroSchedule
schedule
:
import Micro
Micro
.
type MicroSchedule = (attempt: number, elapsed: number) => Option.Option<number>

The MicroSchedule type represents a function that can be used to calculate the delay between repeats.

The function takes the current attempt number and the elapsed time since the first attempt, and returns the delay for the next attempt. If the function returns None, the repetition will stop.

@since3.4.6

MicroSchedule
,
maxAttempt: number
maxAttempt
: number = 7
):
interface Array<T>
Array
<number> => {
let
let attempt: number
attempt
= 1
let
let elapsed: number
elapsed
= 0
const
const out: number[]
out
:
interface Array<T>
Array
<number> = []
let
let duration: Option.Option<number>
duration
=
schedule: (attempt: number, elapsed: number) => Option.Option<number>
schedule
(
let attempt: number
attempt
,
let elapsed: number
elapsed
)
while (
import Option

@since2.0.0

@since2.0.0

Option
.
const isSome: <number>(self: Option.Option<number>) => self is Option.Some<number>

Determine if a Option is a Some.

@paramself - The Option to check.

@example

import { Option } from "effect"
assert.deepStrictEqual(Option.isSome(Option.some(1)), true)
assert.deepStrictEqual(Option.isSome(Option.none()), false)

@since2.0.0

isSome
(
let duration: Option.Option<number>
duration
) &&
let attempt: number
attempt
<=
maxAttempt: number
maxAttempt
) {
const
const value: number
value
=
let duration: Option.Some<number>
duration
.
Some<number>.value: number
value
let attempt: number
attempt
++
let elapsed: number
elapsed
+=
const value: number
value
const out: number[]
out
.
Array<number>.push(...items: number[]): number

Appends new elements to the end of an array, and returns the new length of the array.

@paramitems New elements to add to the array.

push
(
const value: number
value
)
let duration: Option.Option<number>
duration
=
schedule: (attempt: number, elapsed: number) => Option.Option<number>
schedule
(
let attempt: number
attempt
,
let elapsed: number
elapsed
)
}
return
const out: number[]
out
}
const
const policy: Micro.MicroSchedule
policy
=
import Micro
Micro
.
const scheduleIntersect: (self: Micro.MicroSchedule, that: Micro.MicroSchedule) => Micro.MicroSchedule (+1 overload)

Combines two MicroSchedules, by recurring only if both schedules want to recur, using the maximum of the two durations between recurrences.

@since3.4.6

scheduleIntersect
(
import Micro
Micro
.
const scheduleExponential: (baseMillis: number, factor?: number) => Micro.MicroSchedule

Create a MicroSchedule that will generate a delay with an exponential backoff.

@since3.4.6

scheduleExponential
(10),
import Micro
Micro
.
const scheduleSpaced: (millis: number) => Micro.MicroSchedule

Create a MicroSchedule that will generate a constant delay.

@since3.4.6

scheduleSpaced
(300)
)
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
(
const dryRun: (schedule: Micro.MicroSchedule, maxAttempt?: number) => Array<number>
dryRun
(
const policy: Micro.MicroSchedule
policy
))
/*
Output:
[
300, < spaced
300,
300,
300,
320, < exponential
640,
1280
]
*/

One of the fundamental ways to create a fiber is by forking an existing effect. When you fork an effect, it starts executing the effect on a new fiber, giving you a reference to this newly-created fiber.

The following code demonstrates how to create a single fiber using the Micro.fork function. This fiber will execute the function fib(100) independently of the main fiber:

Example (Forking a Fiber)

import {
import Micro
Micro
} from "effect"
const
const fib: (n: number) => Micro.Micro<number>
fib
= (
n: number
n
: number):
import Micro
Micro
.
interface Micro<out A, out E = never, out R = never>

A lightweight alternative to the Effect data type, with a subset of the functionality.

@since3.4.0

@since3.4.0

Micro
<number> =>
n: number
n
< 2
?
import Micro
Micro
.
const succeed: <number>(value: number) => Micro.Micro<number, never, never>

Creates a Micro effect that will succeed with the specified constant value.

@since3.4.0

succeed
(
n: number
n
)
:
import Micro
Micro
.
const zipWith: <number, never, never, number, never, never, number>(self: Micro.Micro<number, never, never>, that: Micro.Micro<number, never, never>, f: (a: number, b: number) => number, options?: {
readonly concurrent?: boolean | undefined;
}) => Micro.Micro<...> (+1 overload)

The Micro.zipWith function combines two Micro effects and allows you to apply a function to the results of the combined effects, transforming them into a single value.

@since3.4.3

zipWith
(
const fib: (n: number) => Micro.Micro<number>
fib
(
n: number
n
- 1),
const fib: (n: number) => Micro.Micro<number>
fib
(
n: number
n
- 2), (
a: number
a
,
b: number
b
) =>
a: number
a
+
b: number
b
)
// ┌─── Micro<MicroFiber<number, never>, never, never>
// ▼
const
const fib10Fiber: Micro.Micro<Micro.MicroFiber<number, never>, never, never>
fib10Fiber
=
import Micro
Micro
.
const fork: <number, never, never>(self: Micro.Micro<number, never, never>) => Micro.Micro<Micro.MicroFiber<number, never>, never, never>

Run the Micro effect in a new MicroFiber that can be awaited, joined, or aborted.

When the parent Micro finishes, this Micro will be aborted.

@since3.4.0

fork
(
const fib: (n: number) => Micro.Micro<number>
fib
(10))

A common operation with fibers is joining them using the Micro.fiberJoin function. This function returns a Micro that will succeed or fail based on the outcome of the fiber it joins:

Example (Joining a Fiber)

import {
import Micro
Micro
} from "effect"
const
const fib: (n: number) => Micro.Micro<number>
fib
= (
n: number
n
: number):
import Micro
Micro
.
interface Micro<out A, out E = never, out R = never>

A lightweight alternative to the Effect data type, with a subset of the functionality.

@since3.4.0

@since3.4.0

Micro
<number> =>
n: number
n
< 2
?
import Micro
Micro
.
const succeed: <number>(value: number) => Micro.Micro<number, never, never>

Creates a Micro effect that will succeed with the specified constant value.

@since3.4.0

succeed
(
n: number
n
)
:
import Micro
Micro
.
const zipWith: <number, never, never, number, never, never, number>(self: Micro.Micro<number, never, never>, that: Micro.Micro<number, never, never>, f: (a: number, b: number) => number, options?: {
readonly concurrent?: boolean | undefined;
}) => Micro.Micro<...> (+1 overload)

The Micro.zipWith function combines two Micro effects and allows you to apply a function to the results of the combined effects, transforming them into a single value.

@since3.4.3

zipWith
(
const fib: (n: number) => Micro.Micro<number>
fib
(
n: number
n
- 1),
const fib: (n: number) => Micro.Micro<number>
fib
(
n: number
n
- 2), (
a: number
a
,
b: number
b
) =>
a: number
a
+
b: number
b
)
// ┌─── Micro<MicroFiber<number, never>, never, never>
// ▼
const
const fib10Fiber: Micro.Micro<Micro.MicroFiber<number, never>, never, never>
fib10Fiber
=
import Micro
Micro
.
const fork: <number, never, never>(self: Micro.Micro<number, never, never>) => Micro.Micro<Micro.MicroFiber<number, never>, never, never>

Run the Micro effect in a new MicroFiber that can be awaited, joined, or aborted.

When the parent Micro finishes, this Micro will be aborted.

@since3.4.0

fork
(
const fib: (n: number) => Micro.Micro<number>
fib
(10))
const
const program: Micro.Micro<void, never, never>
program
=
import Micro
Micro
.
const gen: <unknown, YieldWrap<Micro.Micro<Micro.MicroFiber<number, never>, never, never>> | YieldWrap<Micro.Micro<number, never, never>>, void>(...args: [self: ...] | [body: ...]) => Micro.Micro<...>

@since3.4.0

gen
(function* () {
// Retrieve the fiber
const
const fiber: Micro.MicroFiber<number, never>
fiber
= yield*
const fib10Fiber: Micro.Micro<Micro.MicroFiber<number, never>, never, never>
fib10Fiber
// Join the fiber and get the result
const
const n: number
n
= yield*
import Micro
Micro
.
const fiberJoin: <number, never>(self: Micro.MicroFiber<number, never>) => Micro.Micro<number, never, never>

@since3.11.2

fiberJoin
(
const fiber: Micro.MicroFiber<number, never>
fiber
)
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
(
const n: number
n
)
})
import Micro
Micro
.
const runPromise: <void, never>(effect: Micro.Micro<void, never, never>, options?: {
readonly signal?: AbortSignal | undefined;
readonly scheduler?: Micro.MicroScheduler | undefined;
} | undefined) => Promise<...>

Execute the Micro effect and return a Promise that resolves with the successful value of the computation.

@since3.4.0

runPromise
(
const program: Micro.Micro<void, never, never>
program
)
// Output: 55

Another useful function for fibers is Micro.fiberAwait. This function returns an effect containing a MicroExit value, which provides detailed information about how the fiber completed.

Example (Awaiting Fiber Completion)

import {
import Micro
Micro
} from "effect"
const
const fib: (n: number) => Micro.Micro<number>
fib
= (
n: number
n
: number):
import Micro
Micro
.
interface Micro<out A, out E = never, out R = never>

A lightweight alternative to the Effect data type, with a subset of the functionality.

@since3.4.0

@since3.4.0

Micro
<number> =>
n: number
n
< 2
?
import Micro
Micro
.
const succeed: <number>(value: number) => Micro.Micro<number, never, never>

Creates a Micro effect that will succeed with the specified constant value.

@since3.4.0

succeed
(
n: number
n
)
:
import Micro
Micro
.
const zipWith: <number, never, never, number, never, never, number>(self: Micro.Micro<number, never, never>, that: Micro.Micro<number, never, never>, f: (a: number, b: number) => number, options?: {
readonly concurrent?: boolean | undefined;
}) => Micro.Micro<...> (+1 overload)

The Micro.zipWith function combines two Micro effects and allows you to apply a function to the results of the combined effects, transforming them into a single value.

@since3.4.3

zipWith
(
const fib: (n: number) => Micro.Micro<number>
fib
(
n: number
n
- 1),
const fib: (n: number) => Micro.Micro<number>
fib
(
n: number
n
- 2), (
a: number
a
,
b: number
b
) =>
a: number
a
+
b: number
b
)
// ┌─── Micro<MicroFiber<number, never>, never, never>
// ▼
const
const fib10Fiber: Micro.Micro<Micro.MicroFiber<number, never>, never, never>
fib10Fiber
=
import Micro
Micro
.
const fork: <number, never, never>(self: Micro.Micro<number, never, never>) => Micro.Micro<Micro.MicroFiber<number, never>, never, never>

Run the Micro effect in a new MicroFiber that can be awaited, joined, or aborted.

When the parent Micro finishes, this Micro will be aborted.

@since3.4.0

fork
(
const fib: (n: number) => Micro.Micro<number>
fib
(10))
const
const program: Micro.Micro<void, never, never>
program
=
import Micro
Micro
.
const gen: <unknown, YieldWrap<Micro.Micro<Micro.MicroFiber<number, never>, never, never>> | YieldWrap<Micro.Micro<Micro.MicroExit<number, never>, never, never>>, void>(...args: [self: ...] | [body: ...]) => Micro.Micro<...>

@since3.4.0

gen
(function* () {
// Retrieve the fiber
const
const fiber: Micro.MicroFiber<number, never>
fiber
= yield*
const fib10Fiber: Micro.Micro<Micro.MicroFiber<number, never>, never, never>
fib10Fiber
// Await its completion and get the MicroExit result
const
const exit: Micro.MicroExit<number, never>
exit
= yield*
import Micro
Micro
.
const fiberAwait: <number, never>(self: Micro.MicroFiber<number, never>) => Micro.Micro<Micro.MicroExit<number, never>, never, never>

@since3.11.0

fiberAwait
(
const fiber: Micro.MicroFiber<number, never>
fiber
)
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
(
const exit: Micro.MicroExit<number, never>
exit
)
})
import Micro
Micro
.
const runPromise: <void, never>(effect: Micro.Micro<void, never, never>, options?: {
readonly signal?: AbortSignal | undefined;
readonly scheduler?: Micro.MicroScheduler | undefined;
} | undefined) => Promise<...>

Execute the Micro effect and return a Promise that resolves with the successful value of the computation.

@since3.4.0

runPromise
(
const program: Micro.Micro<void, never, never>
program
)
/*
Output:
{
"_id": "MicroExit",
"_tag": "Success",
"value": 55
}
*/

All effects in Effect are executed by fibers. If you didn’t create the fiber yourself, it was created by an operation you’re using (if it’s concurrent) or by the Effect runtime system.

A fiber is created any time an effect is run. When running effects concurrently, a fiber is created for each concurrent effect.

To summarize:

  • A Micro is a higher-level concept that describes an effectful computation. It is lazy and immutable, meaning it represents a computation that may produce a value or fail but does not immediately execute.
  • A fiber, on the other hand, represents the running execution of a Micro. It can be interrupted or awaited to retrieve its result. Think of it as a way to control and interact with the ongoing computation.

Fibers can be interrupted in various ways. Let’s explore some of these scenarios and see examples of how to interrupt fibers in Effect.

If a fiber’s result is no longer needed, it can be interrupted, which immediately terminates the fiber and safely releases all resources by running all finalizers.

Similar to .await, .interrupt returns a MicroExit value describing how the fiber completed.

Example (Interrupting a Fiber)

import {
import Micro
Micro
} from "effect"
const
const program: Micro.Micro<void, never, never>
program
=
import Micro
Micro
.
const gen: <unknown, YieldWrap<Micro.Micro<void, never, never>>, void>(...args: [self: unknown, body: (this: unknown) => Generator<YieldWrap<Micro.Micro<void, never, never>>, void, never>] | [body: ...]) => Micro.Micro<...>

@since3.4.0

gen
(function* () {
// Fork a fiber that runs indefinitely, printing "Hi!"
const
const fiber: Micro.MicroFiber<never, never>
fiber
= yield*
import Micro
Micro
.
const fork: <never, never, never>(self: Micro.Micro<never, never, never>) => Micro.Micro<Micro.MicroFiber<never, never>, never, never>

Run the Micro effect in a new MicroFiber that can be awaited, joined, or aborted.

When the parent Micro finishes, this Micro will be aborted.

@since3.4.0

fork
(
import Micro
Micro
.
const forever: <void, never, never>(self: Micro.Micro<void, never, never>) => Micro.Micro<never, never, never>

Repeat the given Micro effect forever, only stopping if the effect fails.

@since3.4.0

forever
(
import Micro
Micro
.
const sync: <void>(evaluate: LazyArg<void>) => Micro.Micro<void, never, never>

Creates a Micro effect that succeeds with a lazily evaluated value.

If the evaluation of the value throws an error, the effect will fail with a Die variant of the MicroCause type.

@since3.4.0

sync
(() =>
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
("Hi!")).
Pipeable.pipe<Micro.Micro<void, never, never>, Micro.Micro<void, never, never>>(this: Micro.Micro<...>, ab: (_: Micro.Micro<void, never, never>) => Micro.Micro<void, never, never>): Micro.Micro<...> (+21 overloads)
pipe
(
import Micro
Micro
.
const delay: (millis: number) => <A, E, R>(self: Micro.Micro<A, E, R>) => Micro.Micro<A, E, R> (+1 overload)

Returns an effect that will delay the execution of this effect by the specified duration.

@since3.4.0

delay
(10))
)
)
yield*
import Micro
Micro
.
const sleep: (millis: number) => Micro.Micro<void>

Create a Micro effect that will sleep for the specified duration.

@since3.4.0

sleep
(30)
// Interrupt the fiber
yield*
import Micro
Micro
.
const fiberInterrupt: <never, never>(self: Micro.MicroFiber<never, never>) => Micro.Micro<void>

@since3.11.0

fiberInterrupt
(
const fiber: Micro.MicroFiber<never, never>
fiber
)
})
import Micro
Micro
.
const runPromise: <void, never>(effect: Micro.Micro<void, never, never>, options?: {
readonly signal?: AbortSignal | undefined;
readonly scheduler?: Micro.MicroScheduler | undefined;
} | undefined) => Promise<...>

Execute the Micro effect and return a Promise that resolves with the successful value of the computation.

@since3.4.0

runPromise
(
const program: Micro.Micro<void, never, never>
program
)
/*
Output:
Hi!
Hi!
*/

A fiber can be interrupted using the Micro.interrupt effect on that particular fiber.

Example (Without Interruption)

In this case, the program runs without any interruption, logging the start and completion of the task.

import {
import Micro
Micro
} from "effect"
const
const program: Micro.Micro<void, never, never>
program
=
import Micro
Micro
.
const gen: <unknown, YieldWrap<Micro.Micro<void, never, never>>, void>(...args: [self: unknown, body: (this: unknown) => Generator<YieldWrap<Micro.Micro<void, never, never>>, void, never>] | [body: ...]) => Micro.Micro<...>

@since3.4.0

gen
(function* () {
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
("start")
yield*
import Micro
Micro
.
const sleep: (millis: number) => Micro.Micro<void>

Create a Micro effect that will sleep for the specified duration.

@since3.4.0

sleep
(2_000)
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
("done")
})
import Micro
Micro
.
const runPromiseExit: <void, never>(effect: Micro.Micro<void, never, never>, options?: {
readonly signal?: AbortSignal | undefined;
readonly scheduler?: Micro.MicroScheduler | undefined;
} | undefined) => Promise<...>

Execute the Micro effect and return a Promise that resolves with the MicroExit of the computation.

@since3.4.6

runPromiseExit
(
const program: Micro.Micro<void, never, never>
program
).
Promise<MicroExit<void, never>>.then<void, never>(onfulfilled?: ((value: Micro.MicroExit<void, never>) => void | PromiseLike<void>) | null | undefined, onrejected?: ((reason: any) => PromiseLike<never>) | null | undefined): Promise<...>

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

@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:
start
done
{
"_id": "MicroExit",
"_tag": "Success"
}
*/

Example (With Interruption)

Here, the fiber is interrupted after the log "start" but before the "done" log. The Effect.interrupt stops the fiber, and it never reaches the final log.

import {
import Micro
Micro
} from "effect"
const
const program: Micro.Micro<void, never, never>
program
=
import Micro
Micro
.
const gen: <unknown, YieldWrap<Micro.Micro<void, never, never>>, void>(...args: [self: unknown, body: (this: unknown) => Generator<YieldWrap<Micro.Micro<void, never, never>>, void, never>] | [body: ...]) => Micro.Micro<...>

@since3.4.0

gen
(function* () {
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
("start")
yield*
import Micro
Micro
.
const sleep: (millis: number) => Micro.Micro<void>

Create a Micro effect that will sleep for the specified duration.

@since3.4.0

sleep
(2_000)
yield*
import Micro
Micro
.
const interrupt: Micro.Micro<never, never, never>

Abort the current Micro effect.

@since3.4.6

interrupt
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
("done")
})
import Micro
Micro
.
const runPromiseExit: <void, never>(effect: Micro.Micro<void, never, never>, options?: {
readonly signal?: AbortSignal | undefined;
readonly scheduler?: Micro.MicroScheduler | undefined;
} | undefined) => Promise<...>

Execute the Micro effect and return a Promise that resolves with the MicroExit of the computation.

@since3.4.6

runPromiseExit
(
const program: Micro.Micro<void, never, never>
program
).
Promise<MicroExit<void, never>>.then<void, never>(onfulfilled?: ((value: Micro.MicroExit<void, never>) => void | PromiseLike<void>) | null | undefined, onrejected?: ((reason: any) => PromiseLike<never>) | null | undefined): Promise<...>

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

@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:
start
{
"_id": "MicroExit",
"_tag": "Failure",
"cause": {
"_tag": "Interrupt",
"traces": [],
"name": "MicroCause.Interrupt"
}
}
*/

When a fiber is interrupted, the cause of the interruption is captured, including details like the fiber’s ID and when it started.

When running multiple effects concurrently, such as with Micro.forEach, if one of the effects is interrupted, it causes all concurrent effects to be interrupted as well.

Example (Interrupting Concurrent Effects)

import {
import Micro
Micro
} from "effect"
const
const program: Micro.Micro<void[], never, never>
program
=
import Micro
Micro
.
const forEach: <number, void, never, never>(iterable: Iterable<number>, f: (a: number, index: number) => Micro.Micro<void, never, never>, options?: {
readonly concurrency?: Concurrency | undefined;
readonly discard?: false | undefined;
}) => Micro.Micro<...> (+1 overload)

For each element of the provided iterable, run the effect and collect the results.

If the discard option is set to true, the results will be discarded and the effect will return void.

The concurrency option can be set to control how many effects are run in parallel. By default, the effects are run sequentially.

@since3.4.0

forEach
(
[1, 2, 3],
(
n: number
n
) =>
import Micro
Micro
.
const gen: <unknown, YieldWrap<Micro.Micro<void, never, never>>, void>(...args: [self: unknown, body: (this: unknown) => Generator<YieldWrap<Micro.Micro<void, never, never>>, void, never>] | [body: ...]) => Micro.Micro<...>

@since3.4.0

gen
(function* () {
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
(`start #${
n: number
n
}`)
yield*
import Micro
Micro
.
const sleep: (millis: number) => Micro.Micro<void>

Create a Micro effect that will sleep for the specified duration.

@since3.4.0

sleep
(2 * 1_000)
if (
n: number
n
> 1) {
yield*
import Micro
Micro
.
const interrupt: Micro.Micro<never, never, never>

Abort the current Micro effect.

@since3.4.6

interrupt
}
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
(`done #${
n: number
n
}`)
}),
{
concurrency?: Concurrency | undefined
concurrency
: "unbounded" }
)
import Micro
Micro
.
const runPromiseExit: <void[], never>(effect: Micro.Micro<void[], never, never>, options?: {
readonly signal?: AbortSignal | undefined;
readonly scheduler?: Micro.MicroScheduler | undefined;
} | undefined) => Promise<...>

Execute the Micro effect and return a Promise that resolves with the MicroExit of the computation.

@since3.4.6

runPromiseExit
(
const program: Micro.Micro<void[], never, never>
program
).
Promise<MicroExit<void[], never>>.then<void, never>(onfulfilled?: ((value: Micro.MicroExit<void[], never>) => void | PromiseLike<void>) | null | undefined, onrejected?: ((reason: any) => PromiseLike<never>) | null | undefined): Promise<...>

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

@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
((
exit: Micro.MicroExit<void[], never>
exit
) =>
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
(
var JSON: JSON

An intrinsic object that provides functions to convert JavaScript values to and from the JavaScript Object Notation (JSON) format.

JSON
.
JSON.stringify(value: any, replacer?: (number | string)[] | null, space?: string | number): string (+1 overload)

Converts a JavaScript value to a JavaScript Object Notation (JSON) string.

@paramvalue A JavaScript value, usually an object or array, to be converted.

@paramreplacer An array of strings and numbers that acts as an approved list for selecting the object properties that will be stringified.

@paramspace Adds indentation, white space, and line break characters to the return-value JSON text to make it easier to read.

stringify
(
exit: Micro.MicroExit<void[], never>
exit
, null, 2))
)
/*
Output:
start #1
start #2
start #3
done #1
{
"_id": "MicroExit",
"_tag": "Failure",
"cause": {
"_tag": "Interrupt",
"traces": [],
"name": "MicroCause.Interrupt"
}
}
*/

The Effect.race function allows you to run multiple effects concurrently, returning the result of the first one that successfully completes.

Example (Basic Race Between Effects)

import {
import Micro
Micro
} from "effect"
const
const task1: Micro.Micro<never, string, never>
task1
=
import Micro
Micro
.
const delay: <never, string, never>(self: Micro.Micro<never, string, never>, millis: number) => Micro.Micro<never, string, never> (+1 overload)

Returns an effect that will delay the execution of this effect by the specified duration.

@since3.4.0

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

Creates a Micro effect that fails with the given error.

This results in a Fail variant of the MicroCause type, where the error is tracked at the type level.

@since3.4.0

fail
("task1"), 1_000)
const
const task2: Micro.Micro<string, never, never>
task2
=
import Micro
Micro
.
const delay: <string, never, never>(self: Micro.Micro<string, never, never>, millis: number) => Micro.Micro<string, never, never> (+1 overload)

Returns an effect that will delay the execution of this effect by the specified duration.

@since3.4.0

delay
(
import Micro
Micro
.
const succeed: <string>(value: string) => Micro.Micro<string, never, never>

Creates a Micro effect that will succeed with the specified constant value.

@since3.4.0

succeed
("task2"), 2_000)
// Run both tasks concurrently and return
// the result of the first to complete
const
const program: Micro.Micro<string, string, never>
program
=
import Micro
Micro
.
const race: <never, string, never, string, never, never>(self: Micro.Micro<never, string, never>, that: Micro.Micro<string, never, never>) => Micro.Micro<string, string, never> (+1 overload)

Returns an effect that races two effects, yielding the value of the first effect to succeed. Losers of the race will be interrupted immediately.

@since3.4.0

race
(
const task1: Micro.Micro<never, string, never>
task1
,
const task2: Micro.Micro<string, never, never>
task2
)
import Micro
Micro
.
const runPromise: <string, string>(effect: Micro.Micro<string, string, never>, options?: {
readonly signal?: AbortSignal | undefined;
readonly scheduler?: Micro.MicroScheduler | undefined;
} | undefined) => Promise<...>

Execute the Micro effect and return a Promise that resolves with the successful value of the computation.

@since3.4.0

runPromise
(
const program: Micro.Micro<string, string, never>
program
).
Promise<string>.then<void, never>(onfulfilled?: ((value: string) => void | PromiseLike<void>) | null | undefined, onrejected?: ((reason: any) => PromiseLike<never>) | null | undefined): Promise<...>

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

@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:
task2
*/

If you want to handle the result of whichever task completes first, whether it succeeds or fails, you can use the Micro.either function. This function wraps the result in an Either type, allowing you to see if the result was a success (Right) or a failure (Left):

Example (Handling Success or Failure with Either)

import {
import Micro
Micro
} from "effect"
const
const task1: Micro.Micro<never, string, never>
task1
=
import Micro
Micro
.
const delay: <never, string, never>(self: Micro.Micro<never, string, never>, millis: number) => Micro.Micro<never, string, never> (+1 overload)

Returns an effect that will delay the execution of this effect by the specified duration.

@since3.4.0

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

Creates a Micro effect that fails with the given error.

This results in a Fail variant of the MicroCause type, where the error is tracked at the type level.

@since3.4.0

fail
("task1"), 1_000)
const
const task2: Micro.Micro<string, never, never>
task2
=
import Micro
Micro
.
const delay: <string, never, never>(self: Micro.Micro<string, never, never>, millis: number) => Micro.Micro<string, never, never> (+1 overload)

Returns an effect that will delay the execution of this effect by the specified duration.

@since3.4.0

delay
(
import Micro
Micro
.
const succeed: <string>(value: string) => Micro.Micro<string, never, never>

Creates a Micro effect that will succeed with the specified constant value.

@since3.4.0

succeed
("task2"), 2_000)
// Run both tasks concurrently, wrapping the result
// in Either to capture success or failure
const
const program: Micro.Micro<Either<never, string> | Either<string, never>, never, never>
program
=
import Micro
Micro
.
const race: <Either<never, string>, never, never, Either<string, never>, never, never>(self: Micro.Micro<Either<never, string>, never, never>, that: Micro.Micro<Either<string, never>, never, never>) => Micro.Micro<...> (+1 overload)

Returns an effect that races two effects, yielding the value of the first effect to succeed. Losers of the race will be interrupted immediately.

@since3.4.0

race
(
import Micro
Micro
.
const either: <never, string, never>(self: Micro.Micro<never, string, never>) => Micro.Micro<Either<never, string>, never, never>

Replace the success value of the given Micro effect with an Either, wrapping the success value in Right and wrapping any expected errors with a Left.

@since3.4.0

either
(
const task1: Micro.Micro<never, string, never>
task1
),
import Micro
Micro
.
const either: <string, never, never>(self: Micro.Micro<string, never, never>) => Micro.Micro<Either<string, never>, never, never>

Replace the success value of the given Micro effect with an Either, wrapping the success value in Right and wrapping any expected errors with a Left.

@since3.4.0

either
(
const task2: Micro.Micro<string, never, never>
task2
))
import Micro
Micro
.
const runPromise: <Either<never, string> | Either<string, never>, never>(effect: Micro.Micro<Either<never, string> | Either<string, never>, never, never>, options?: {
readonly signal?: AbortSignal | undefined;
readonly scheduler?: Micro.MicroScheduler | undefined;
} | undefined) => Promise<...>

Execute the Micro effect and return a Promise that resolves with the successful value of the computation.

@since3.4.0

runPromise
(
const program: Micro.Micro<Either<never, string> | Either<string, never>, never, never>
program
).
Promise<Either<never, string> | Either<string, never>>.then<void, never>(onfulfilled?: ((value: Either<never, string> | Either<string, never>) => void | PromiseLike<void>) | null | undefined, onrejected?: ((reason: any) => PromiseLike<...>) | null | undefined): Promise<...>

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

@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: 'Either', _tag: 'Left', left: 'task1' }
*/