Control Flow Operators
Use ordinary JavaScript branches and loops for sequential effect work, and Effect's control-flow combinators for concurrency, structured collection, and alternate failure modes. Combinators accept Effect values directly and decide when and how each Effect runs.
| Operator | Use when |
|---|---|
Effect.when | Running an Effect conditionally based on an Effectful predicate |
Effect.zip / Effect.zipWith | Pairing two Effects sequentially or concurrently |
Effect.whileLoop | Repeating an Effect from an options object in operator style |
forEach | Mapping or iterating a collection with optional concurrency or { discard: true } |
all | Running tuples, iterables, or records of Effects with concurrency or { mode: "result" } |
Branching and conditional computations
error InvalidSize {
size: number
}
function optionalSize(size: number) {
if (size < 0) return Option.none<number>()
return Option.some(size)
}
effect function requiredSize(size: number) {
if (size < 0) throw new InvalidSize({ size })
return size
}
// number!InvalidSize
effect function announceIfEnabled(enabled: boolean) {
return try Effect.when(effect {
try Console.log("notifications enabled")
return "announced"
}, succeed(enabled))
}
// Run in an effect function:
// try Console.log(Option.isNone(optionalSize(-1)), Option.getOrNull(optionalSize(3)), try requiredSize(3))
// try Console.log(requiredSize(-1) catch (error) => `${error._tag} ${error.size}`)
// try Console.log(Option.isNone(try announceIfEnabled(false)))
// try Console.log(Option.getOrNull(try announceIfEnabled(true)))true 3 3
InvalidSize -1
true
notifications enabled
announcedif, early return, and throw work directly inside effect functions, including after service calls. Effect.when evaluates its condition Effect first, runs the body only if it yields true, and returns Option.Some or Option.None; a condition failure propagates immediately.
Combining two results
effect function amount() {
try sleep("30 millis")
return 18
}
effect function currency() {
try sleep("10 millis")
return "USD"
}
effect function sequentialPair() {
const value = try amount()
const unit = try currency()
return [value, unit] as const
}
effect function concurrentPair() {
return try Effect.zip(amount(), currency(), { concurrent: true })
}
effect function formattedPair() {
return try Effect.zipWith(
amount(),
currency(),
(value, unit) => `${value} ${unit}`
)
}
// Run in an effect function:
// {
// const jsonValue = [try sequentialPair(), try concurrentPair(), try formattedPair()]
// try Console.log(try Effect.try(() => JSON.stringify(jsonValue)))
// }[[18,"USD"],[18,"USD"],"18 USD"]Effect.zip returns a tuple and Effect.zipWith combines both results synchronously. Both run left-to-right by default; { concurrent: true } starts both Effects together while preserving tuple order, interrupting and cleaning up the sibling if either fails.
Repeating work in loops
effect function inspectPages() {
const inspected: number[] = []
let page = 1
while (page <= 3) {
try sleep("10 millis")
inspected.push(page)
page++
}
return inspected // [1, 2, 3]
}
effect function logAttempts() {
for (let attempt = 1; attempt <= 3; attempt++) {
try Console.log(`attempt ${attempt}`)
}
}
// Run in an effect function:
// {
// const jsonValue = try inspectPages()
// try Console.log(try Effect.try(() => JSON.stringify(jsonValue)))
// }
// try logAttempts()
// Output: [1,2,3]
// Output: attempt 1
// Output: attempt 2
// Output: attempt 3Standard while and for loops support try, break, continue, and throw, recreating local state on each invocation. Collect into an array only when callers need the accumulated values; otherwise a loop completes with void.
effect function operatorLoop() {
let index = 0
try Effect.whileLoop({
while: () => index < 3,
body: () => Console.log(`iteration ${index}`),
step: () => { index++ }
})
}
// Run in an effect function: try operatorLoop()iteration 0
iteration 1
iteration 2In Effect 4.1.1, Effect.whileLoop takes one options object (while, body, step) and returns a void Effect. body constructs the iteration's Effect lazily and step advances state synchronously after each success; store accumulated values in local state if needed.
Traversing collections and discarding values
effect function prepare(id: number) {
try sleep("10 millis")
return `prepared-${id}`
}
effect function prepareAll() {
return try forEach([3, 5, 8], effect (id, index) => {
try Console.log(`preparing position ${index}`)
return try prepare(id)
}, { concurrency: 2 })
}
effect function logAll() {
try forEach([3, 5, 8], (id) => Console.log(`id ${id}`), { discard: true })
}
// Run in an effect function:
// {
// const jsonValue = try prepareAll()
// try Console.log(try Effect.try(() => JSON.stringify(jsonValue)))
// }
// try logAll()preparing position 0
preparing position 1
preparing position 2
["prepared-3","prepared-5","prepared-8"]
id 3
id 5
id 8forEach runs sequentially by default and preserves input order in the returned array. Passing concurrency bounds overlapping callbacks, and { discard: true } omits result allocation. Any failure stops traversal, interrupting and finalizing in-flight siblings.
Collecting programs
effect function collected() {
const tuple = try all([succeed(12), succeed("ready")] as const)
const object = try all({ count: succeed(12), status: succeed("ready") })
const iterable = new Set([prepare(3), prepare(5)])
const array = try all(iterable, { concurrency: 2 })
return { tuple, object, array }
}
// tuple: [12, "ready"]
// object: { count: 12, status: "ready" }
// array contains the two prepared values in iteration order.
// Run in an effect function:
// {
// const jsonValue = try collected()
// try Console.log(try Effect.try(() => JSON.stringify(jsonValue)))
// }
// Output: {"tuple":[12,"ready"],"object":{"count":12,"status":"ready"},"array":["prepared-3","prepared-5"]}all accepts tuples, iterables, objects, and records of Effects and returns results in the matching shape. Constructing the collection does not start its Effects; execution is sequential unless concurrency is set, and { discard: true } drops the combined value.
Early termination and alternate collection modes
error Unavailable {
id: number
}
effect function load(id: number) {
if (id === 5) throw new Unavailable({ id })
try Console.log(`loaded ${id}`)
return `item-${id}`
}
effect function stopAtFailure() {
return try all([load(3), load(5), load(8)])
}
// Sequentially loads 3, then fails with Unavailable; 8 is not started.
effect function collectOutcomes() {
return try all([load(3), load(5), load(8)], { mode: "result" })
}
// [Result.succeed("item-3"), Result.fail(Unavailable), Result.succeed("item-8")]
// Run in an effect function:
// try Console.log(stopAtFailure() catch (error) => error._tag)
// {
// const jsonValue = (try collectOutcomes()).map((result) => Result.isSuccess(result) ? result.success : result.failure._tag)
// try Console.log(try Effect.try(() => JSON.stringify(jsonValue)))
// }
// Output: loaded 3
// Output: Unavailable
// Output: loaded 3
// Output: loaded 8
// Output: ["item-3","Unavailable","item-8"]By default, all aborts on the first typed failure and propagates it in E. With { mode: "result" }, every Effect runs to completion and each typed outcome is captured as a Result; defects and interruption still abort the collection.
Coming from Effect
Write sequential logic with try and standard statements. Pass work() directly to combinators expecting an Effect, and use effect { ... } or an effect arrow when building an inline Effect value.
The matching Effect page: effect.website/docs/v4/code-style/control-flow