To execute an effect, you can use one of the many run functions provided by the Effect module.
runSync
Executes an effect synchronously, running it immediately and returning the result.
Example (Synchronous Logging)
Use Effect.runSync to run an effect that does not fail and does not include any asynchronous operations. If the effect fails or involves asynchronous work, it will throw an error, and execution will stop where the failure or async operation occurs.
Example (Incorrect Usage with Failing or Async Effects)
Executes an effect synchronously and returns its result.
Use runSync when you are certain that the effect is purely synchronous and will not perform any asynchronous operations.
If the effect fails or contains asynchronous tasks, it will throw an error.
@example
import { Effect } from "effect"
// Define a synchronous effect
const program = Effect.sync(() => {
console.log("Hello, World!")
return 1
})
// Execute the effect synchronously
const result = Effect.runSync(program)
// Output: Hello, World!
Creates an Effect that represents a recoverable error.
This Effect does not succeed but instead fails with the provided error. The
failure can be of any type, and will propagate through the effect pipeline
unless handled.
Use this function when you want to explicitly signal an error in an Effect
computation. The failed effect can later be handled with functions like
catchAll
or
catchTag
.
@example
import { Effect } from "effect"
// Example of creating a failed effect
const failedEffect = Effect.fail("Something went wrong")
// Handle the failure
failedEffect.pipe(
Effect.catchAll((error) => Effect.succeed(Recovered from: ${error})),
Effect.runPromise
).then(console.log)
// Output: "Recovered from: Something went wrong"
@since ― 2.0.0
fail("my error"))
6
} catch (
var e:unknown
e) {
7
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(newError('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
constname='Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr
Example using the Console class:
constout=getStreamSomehow();
consterr=getStreamSomehow();
constmyConsole=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(newError('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
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()).
constcode=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.
@since ― v0.1.100
error(
var e:unknown
e)
8
}
9
/*
10
Output:
11
(FiberFailure) Error: my error
12
*/
13
14
try {
15
// Attempt to run an effect that involves async work
Executes an effect synchronously and returns its result.
Use runSync when you are certain that the effect is purely synchronous and will not perform any asynchronous operations.
If the effect fails or contains asynchronous tasks, it will throw an error.
@example
import { Effect } from "effect"
// Define a synchronous effect
const program = Effect.sync(() => {
console.log("Hello, World!")
return 1
})
// Execute the effect synchronously
const result = Effect.runSync(program)
// Output: Hello, World!
Creates a new resolved promise for the provided value.
@param ― value A promise.
@returns ― A promise whose internal state matches the provided promise.
resolve(1)))
17
} catch (
var e:unknown
e) {
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(newError('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
constname='Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr
Example using the Console class:
constout=getStreamSomehow();
consterr=getStreamSomehow();
constmyConsole=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(newError('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
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()).
constcode=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.
@since ― v0.1.100
error(
var e:unknown
e)
19
}
20
/*
21
Output:
22
(FiberFailure) AsyncFiberException: Fiber #0 cannot be resolved synchronously. This is caused by using runSync on an effect that performs async work
23
*/
runSyncExit
Runs an effect synchronously and returns the result as an Exit type, which represents the outcome (success or failure) of the effect.
Use Effect.runSyncExit to find out whether an effect succeeded or failed,
including any defects, without dealing with asynchronous operations.
The Exit type represents the result of the effect:
If the effect succeeds, the result is wrapped in a Success.
If it fails, the failure information is provided as a Failure containing
a Cause type.
Example (Handling Results as Exit)
1
import {
import Effect
@since ― 2.0.0
@since ― 2.0.0
@since ― 2.0.0
Effect } from"effect"
2
3
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(newError('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
constname='Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr
Example using the Console class:
constout=getStreamSomehow();
consterr=getStreamSomehow();
constmyConsole=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(newError('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
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()).
Executes an effect synchronously and returns an Exit describing the result.
Use runSyncExit when you need detailed information about the outcome of the effect,
including whether it succeeded or failed, without throwing exceptions.
@example
import { Effect } from "effect"
// Execute a successful effect and get the Exit result
const result1 = Effect.runSyncExit(Effect.succeed(1))
console.log(result1)
// Output:
// {
// _id: "Exit",
// _tag: "Success",
// value: 1
// }
// Execute a failing effect and get the Exit result
const result2 = Effect.runSyncExit(Effect.fail("my error"))
console.log(result2)
// Output:
// {
// _id: "Exit",
// _tag: "Failure",
// cause: {
// _id: "Cause",
// _tag: "Fail",
// failure: "my error"
// }
// }
Creates an Effect that succeeds with the provided value.
Use this function to represent a successful computation that yields a value of type A.
The effect does not fail and does not require any environmental context.
@example
import { Effect } from "effect"
// Creating an effect that succeeds with the number 42
const success = Effect.succeed(42)
@since ― 2.0.0
succeed(1)))
4
/*
5
Output:
6
{
7
_id: "Exit",
8
_tag: "Success",
9
value: 1
10
}
11
*/
12
13
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(newError('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
constname='Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr
Example using the Console class:
constout=getStreamSomehow();
consterr=getStreamSomehow();
constmyConsole=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(newError('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
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()).
Executes an effect synchronously and returns an Exit describing the result.
Use runSyncExit when you need detailed information about the outcome of the effect,
including whether it succeeded or failed, without throwing exceptions.
@example
import { Effect } from "effect"
// Execute a successful effect and get the Exit result
const result1 = Effect.runSyncExit(Effect.succeed(1))
console.log(result1)
// Output:
// {
// _id: "Exit",
// _tag: "Success",
// value: 1
// }
// Execute a failing effect and get the Exit result
const result2 = Effect.runSyncExit(Effect.fail("my error"))
console.log(result2)
// Output:
// {
// _id: "Exit",
// _tag: "Failure",
// cause: {
// _id: "Cause",
// _tag: "Fail",
// failure: "my error"
// }
// }
Creates an Effect that represents a recoverable error.
This Effect does not succeed but instead fails with the provided error. The
failure can be of any type, and will propagate through the effect pipeline
unless handled.
Use this function when you want to explicitly signal an error in an Effect
computation. The failed effect can later be handled with functions like
catchAll
or
catchTag
.
@example
import { Effect } from "effect"
// Example of creating a failed effect
const failedEffect = Effect.fail("Something went wrong")
// Handle the failure
failedEffect.pipe(
Effect.catchAll((error) => Effect.succeed(Recovered from: ${error})),
Effect.runPromise
).then(console.log)
// Output: "Recovered from: Something went wrong"
@since ― 2.0.0
fail("my error")))
14
/*
15
Output:
16
{
17
_id: "Exit",
18
_tag: "Failure",
19
cause: {
20
_id: "Cause",
21
_tag: "Fail",
22
failure: "my error"
23
}
24
}
25
*/
If the effect contains asynchronous operations, Effect.runSyncExit will
return an Failure with a Die cause, indicating that the effect cannot be
resolved synchronously.
Example (Asynchronous Operation Resulting in Die)
1
import {
import Effect
@since ― 2.0.0
@since ― 2.0.0
@since ― 2.0.0
Effect } from"effect"
2
3
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(newError('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
constname='Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr
Example using the Console class:
constout=getStreamSomehow();
consterr=getStreamSomehow();
constmyConsole=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(newError('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
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()).
Executes an effect synchronously and returns an Exit describing the result.
Use runSyncExit when you need detailed information about the outcome of the effect,
including whether it succeeded or failed, without throwing exceptions.
@example
import { Effect } from "effect"
// Execute a successful effect and get the Exit result
const result1 = Effect.runSyncExit(Effect.succeed(1))
console.log(result1)
// Output:
// {
// _id: "Exit",
// _tag: "Success",
// value: 1
// }
// Execute a failing effect and get the Exit result
const result2 = Effect.runSyncExit(Effect.fail("my error"))
console.log(result2)
// Output:
// {
// _id: "Exit",
// _tag: "Failure",
// cause: {
// _id: "Cause",
// _tag: "Fail",
// failure: "my error"
// }
// }
Creates a new resolved promise for the provided value.
@param ― value A promise.
@returns ― A promise whose internal state matches the provided promise.
resolve(1))))
4
/*
5
Output:
6
{
7
_id: 'Exit',
8
_tag: 'Failure',
9
cause: {
10
_id: 'Cause',
11
_tag: 'Die',
12
defect: [Fiber #0 cannot be resolved synchronously. This is caused by using runSync on an effect that performs async work] {
13
fiber: [FiberRuntime],
14
_tag: 'AsyncFiberException',
15
name: 'AsyncFiberException'
16
}
17
}
18
}
19
*/
runPromise
Executes an effect and returns the result as a Promise.
Use Effect.runPromise when you need to execute an effect and work with the
result using Promise syntax, typically for compatibility with other
promise-based code.
Example (Running a Successful Effect as a Promise)
Executes an effect and returns a Promise that resolves with the result.
Use runPromise when working with asynchronous effects and you need to integrate with code that uses Promises.
If the effect fails, the returned Promise will be rejected with the error.
@example
import { Effect } from "effect"
// Execute an effect and handle the result with a Promise
Effect.runPromise(Effect.succeed(1)).then(console.log) // Output: 1
// Execute a failing effect and handle the rejection
Effect.runPromise(Effect.fail("my error")).catch((error) => {
console.error("Effect failed with error:", error)
})
Creates an Effect that succeeds with the provided value.
Use this function to represent a successful computation that yields a value of type A.
The effect does not fail and does not require any environmental context.
@example
import { Effect } from "effect"
// Creating an effect that succeeds with the number 42
const success = Effect.succeed(42)
Attaches callbacks for the resolution and/or rejection of the Promise.
@param ― onfulfilled The callback to execute when the Promise is resolved.
@param ― onrejected The callback to execute when the Promise is rejected.
@returns ― A 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(newError('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
constname='Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr
Example using the Console class:
constout=getStreamSomehow();
consterr=getStreamSomehow();
constmyConsole=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(newError('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
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()).
Executes an effect and returns a Promise that resolves with the result.
Use runPromise when working with asynchronous effects and you need to integrate with code that uses Promises.
If the effect fails, the returned Promise will be rejected with the error.
@example
import { Effect } from "effect"
// Execute an effect and handle the result with a Promise
Effect.runPromise(Effect.succeed(1)).then(console.log) // Output: 1
// Execute a failing effect and handle the rejection
Effect.runPromise(Effect.fail("my error")).catch((error) => {
console.error("Effect failed with error:", error)
})
Creates an Effect that represents a recoverable error.
This Effect does not succeed but instead fails with the provided error. The
failure can be of any type, and will propagate through the effect pipeline
unless handled.
Use this function when you want to explicitly signal an error in an Effect
computation. The failed effect can later be handled with functions like
catchAll
or
catchTag
.
@example
import { Effect } from "effect"
// Example of creating a failed effect
const failedEffect = Effect.fail("Something went wrong")
// Handle the failure
failedEffect.pipe(
Effect.catchAll((error) => Effect.succeed(Recovered from: ${error})),
Effect.runPromise
).then(console.log)
// Output: "Recovered from: Something went wrong"
Attaches a callback for only the rejection of the Promise.
@param ― onrejected The callback to execute when the Promise is rejected.
@returns ― A Promise for the completion of the callback.
catch(
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(newError('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
constname='Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr
Example using the Console class:
constout=getStreamSomehow();
consterr=getStreamSomehow();
constmyConsole=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(newError('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
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()).
constcode=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.
@since ― v0.1.100
error)
4
/*
5
Output:
6
(FiberFailure) Error: my error
7
*/
runPromiseExit
Runs an effect and returns a Promise that resolves to an Exit, which
represents the outcome (success or failure) of the effect.
Use Effect.runPromiseExit when you need to determine if an effect succeeded
or failed, including any defects, and you want to work with a Promise.
The Exit type represents the result of the effect:
If the effect succeeds, the result is wrapped in a Success.
If it fails, the failure information is provided as a Failure containing
a Cause type.
Executes an effect and returns a Promise that resolves with an Exit describing the result.
Use runPromiseExit when you need detailed information about the outcome of the effect, including success or failure,
and you want to work with Promises.
@example
import { Effect } from "effect"
// Execute a successful effect and get the Exit result as a Promise
Effect.runPromiseExit(Effect.succeed(1)).then(console.log)
// Output:
// {
// _id: "Exit",
// _tag: "Success",
// value: 1
// }
// Execute a failing effect and get the Exit result as a Promise
Effect.runPromiseExit(Effect.fail("my error")).then(console.log)
// Output:
// {
// _id: "Exit",
// _tag: "Failure",
// cause: {
// _id: "Cause",
// _tag: "Fail",
// failure: "my error"
// }
// }
Creates an Effect that succeeds with the provided value.
Use this function to represent a successful computation that yields a value of type A.
The effect does not fail and does not require any environmental context.
@example
import { Effect } from "effect"
// Creating an effect that succeeds with the number 42
const success = Effect.succeed(42)
Attaches callbacks for the resolution and/or rejection of the Promise.
@param ― onfulfilled The callback to execute when the Promise is resolved.
@param ― onrejected The callback to execute when the Promise is rejected.
@returns ― A 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(newError('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
constname='Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr
Example using the Console class:
constout=getStreamSomehow();
consterr=getStreamSomehow();
constmyConsole=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(newError('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
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()).
Executes an effect and returns a Promise that resolves with an Exit describing the result.
Use runPromiseExit when you need detailed information about the outcome of the effect, including success or failure,
and you want to work with Promises.
@example
import { Effect } from "effect"
// Execute a successful effect and get the Exit result as a Promise
Effect.runPromiseExit(Effect.succeed(1)).then(console.log)
// Output:
// {
// _id: "Exit",
// _tag: "Success",
// value: 1
// }
// Execute a failing effect and get the Exit result as a Promise
Effect.runPromiseExit(Effect.fail("my error")).then(console.log)
// Output:
// {
// _id: "Exit",
// _tag: "Failure",
// cause: {
// _id: "Cause",
// _tag: "Fail",
// failure: "my error"
// }
// }
Creates an Effect that represents a recoverable error.
This Effect does not succeed but instead fails with the provided error. The
failure can be of any type, and will propagate through the effect pipeline
unless handled.
Use this function when you want to explicitly signal an error in an Effect
computation. The failed effect can later be handled with functions like
catchAll
or
catchTag
.
@example
import { Effect } from "effect"
// Example of creating a failed effect
const failedEffect = Effect.fail("Something went wrong")
// Handle the failure
failedEffect.pipe(
Effect.catchAll((error) => Effect.succeed(Recovered from: ${error})),
Effect.runPromise
).then(console.log)
// Output: "Recovered from: Something went wrong"
Attaches callbacks for the resolution and/or rejection of the Promise.
@param ― onfulfilled The callback to execute when the Promise is resolved.
@param ― onrejected The callback to execute when the Promise is rejected.
@returns ― A 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(newError('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
constname='Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr
Example using the Console class:
constout=getStreamSomehow();
consterr=getStreamSomehow();
constmyConsole=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(newError('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
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()).
The foundational function for running effects, returning a “fiber” that can be observed or interrupted.
Effect.runFork is used to run an effect in the background by creating a fiber. It is the base function
for all other run functions. It starts a fiber that can be observed or interrupted.
The repeat function returns a new effect that repeats the given effect
according to a specified schedule or until the first failure. The scheduled
recurrences are in addition to the initial execution, so Effect.repeat(action, Schedule.once) executes action once initially, and if it succeeds, repeats it
an additional time.
@example
// Success Example
import { Effect, Schedule, Console } from "effect"
Executes an effect and returns a RuntimeFiber that represents the running computation.
Use runFork when you want to start an effect without blocking the current execution flow.
It returns a fiber that you can observe, interrupt, or join as needed.
@example
import { Effect, Console, Schedule, Fiber } from "effect"
// Define an effect that repeats a message every 200 milliseconds
const program = Effect.repeat(
Console.log("running..."),
Schedule.spaced("200 millis")
)
// Start the effect without blocking
const fiber = Effect.runFork(program)
// Interrupt the fiber after 500 milliseconds
setTimeout(() => {
Effect.runFork(Fiber.interrupt(fiber))
}, 500)
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().
@since ― v0.0.1
@param ― callback The function to call when the timer elapses.
@param ― delay The number of milliseconds to wait before calling the callback.
@param ― args Optional arguments to pass when the callback is called.
Executes an effect and returns a RuntimeFiber that represents the running computation.
Use runFork when you want to start an effect without blocking the current execution flow.
It returns a fiber that you can observe, interrupt, or join as needed.
@example
import { Effect, Console, Schedule, Fiber } from "effect"
// Define an effect that repeats a message every 200 milliseconds
const program = Effect.repeat(
Console.log("running..."),
Schedule.spaced("200 millis")
)
// Start the effect without blocking
const fiber = Effect.runFork(program)
// Interrupt the fiber after 500 milliseconds
setTimeout(() => {
Effect.runFork(Fiber.interrupt(fiber))
}, 500)
Interrupts the fiber from whichever fiber is calling this method. If the
fiber has already exited, the returned effect will resume immediately.
Otherwise, the effect will resume when the fiber exits.
@since ― 2.0.0
interrupt(
constfiber:Fiber.RuntimeFiber<number, never>
fiber))
16
}, 500)
In this example, the program continuously logs “running…” with each repetition spaced 200 milliseconds apart. You can learn more about repetitions and scheduling in our Introduction to Scheduling guide.
To stop the execution of the program, we use Fiber.interrupt on the fiber returned by Effect.runFork. This allows you to control the execution flow and terminate it when necessary.
For a deeper understanding of how fibers work and how to handle interruptions, check out our guides on Fibers and Interruptions.
Synchronous vs. Asynchronous Effects
In the Effect library, there is no built-in way to determine in advance whether an effect will execute synchronously or asynchronously. While this idea was considered in earlier versions of Effect, it was ultimately not implemented for a few important reasons:
Complexity: Introducing this feature to track sync/async behavior in the type system would make Effect more complex to use and limit its composability.
Safety Concerns: We experimented with different approaches to track asynchronous Effects, but they all resulted in a worse developer experience without significantly improving safety. Even with fully synchronous types, we needed to support a fromCallback combinator to work with APIs using Continuation-Passing Style (CPS). However, at the type level, it’s impossible to guarantee that such a function is always called immediately and not deferred.
Best Practices for Running Effects
In most cases, effects are run at the outermost parts of your application. Typically, an application built around Effect will involve a single call to the main effect. Here’s how you should approach effect execution:
Use runPromise or runFork: For most cases, asynchronous execution should be the default. These methods provide the best way to handle Effect-based workflows.
Use runSync only when necessary: Synchronous execution should be considered an edge case, used only in scenarios where asynchronous execution is not feasible. For example, when you are sure the effect is purely synchronous and need immediate results.
Cheatsheet
The table provides a summary of the available run* functions, along with their input and output types, allowing you to choose the appropriate function based on your needs.
API
Given
Result
runSync
Effect<A, E>
A
runSyncExit
Effect<A, E>
Exit<A, E>
runPromise
Effect<A, E>
Promise<A>
runPromiseExit
Effect<A, E>
Promise<Exit<A, E>>
runFork
Effect<A, E>
RuntimeFiber<A, E>
You can find the complete list of run* functions here.