Chaining Tasks

The Task class is the core of this library. Below are all the methods that can be called on a task. To create a new task, refer to Creating Tasks.

cancel

Cancels a task, meaning it will never complete.

const task = Task.of(5).cancel()

map

Given a task, when it has succeeded, pass the value through a mapping function.

const task: Task<never, number> = Task.of(5).map(number => number * 2)

mapError

Given a task, when it has failed, pass the error through a mapping function to produce a different failed Task.

const task: Task<never, number> = Task.fail(5).mapError(number => number * 2)

errorUnion

Expand the error types of a task. Purely a TypeScript type system modification.

const task: Task<number | AnotherErrorPossibility, number> =
  Task.fail(5).errorUnion<AnotherErrorPossibility>()

validateError

Given a task with an unknown error type, use a type guard to validate the type.

const task: Task<string, number> = Task.fromPromise(fetch(URL)).validateError(
  isString,
)

mapBoth

Given a task, provide mapping functions for both the success and fail states. Results in a new task which has the type of the two mapping function results.

const task: Task<Error, number> = Task.of(5).mapBoth(
  () => new Error("Surprising Error"),
  number => number * 2,
)

chain

Given a task, chain a subsequent task to run after the initial task has succeeded.

In general, users have difficulty understanding the difference between chain and map. The key is to look at the types. chain recieves a value and returns a Task. This allows chaining of asynchronous tasks.

const task: Task<never, number> = Task.of(5).chain(number =>
  Task.of(number * 2),
)

wait

Given a task, wait some number of milliseconds to forward the successful value. Errors still propagate immediately.

const task: Task<never, number> = Task.of(5).wait(2000)

retryIn

Given a failing task, wait some number of seconds and attempt to retry it. Useful for network-related tasks.

const task: Task<never, Response> = Task.fromLazyPromise(() =>
  fetch(URL),
).retryIn(2000)

retryWithExponentialBackoff

Given a task, continue to retry it some number of times. The time between each attempt increases exponentially. Useful for network-related tasks.

const task: Task<never, Response> = Task.fromLazyPromise(() =>
  fetch(URL),
).retryWithExponentialBackoff(2000, 5)

flatten

Given a task which succeeds with another task, flatten into a single task which succeeds with the result of that nested task. Often this can be avoided by using chain.

const task: Task<never, number> = Task.of(Task.of(5)).flatten()

orElse

Given a task that fails, a function can be called to attempt a recovery. This is like chain, but handles the error case instead of the success.

const task: Task<string, string> = Task.fail("Error").orElse(() =>
  Task.of("Success"),
)

fold

Given a task, provide a function to convert each of the success or error states to a value of the same type. Useful for React where you want to choose between rendering JSX that states the error or rendering JSX which shows the data.

const task: Task<unknown, JSX> = Task.fromPromise(fetch(URL)).fold(
  () => <h1>Error</h1>,
  data => <h1>Worked: ${data}</h1>,
)

tap

Given a task, pass the success value to the tap (like tapping a tree or process) to perform some side-effect. Regardless of the return value of the tap, the original success value flows through to the next step.

const task: Task<never, number> = Task.of(5).tap(num => console.log("Got", num))

tapChain

Given a task, pass the success value to the tap (like tapping a tree or process) to perform some side-effect. Regardless of the return value of the tap, the original success value flows through to the next step.

const task: Task<never, number> = Task.of(5).tap(num => console.log("Got", num))

onlyOnce

By default, tasks are run (forked) whenever a downstream function asks for the result. This means if two pieces of code use (or chain from) the same task, it will execute twice. If you want to share the successful result, basically caching it, onlyOnce will create a task that can be shared.

const task: Task<never, Response> = Task.fromLazyPromise(() =>
  fetch(URL)
).onlyOnce();

// Only loads data from network once.
for (let i = 0; i < 5, i++) {
  task.fork(
    () => console.error("Error"),
    resp => console.log(resp)
  );
}

succeedIf

Like onlyOnce, but provides a function which can arbitrarily check whether the task has succeeded. Useful for building tasks off of global state and side effects.

// Succeed until some unknown date.
const task: Task<never, number> = Task.of(5).succeedIf(() => Date.now() < x)

toPromise

Converts a task to a Promise. Useful for integrating with other libraries.

const promise: Promise<number> = Task.of(5).toPromise()

swap

Swaps the error and success values so the old error message in the new success and vice versa. Useful in the rare case where the error is actually the expected outcome.

const task: Task<never, number> = Task.of(5)
const swapped: Task<number, never> = task.swap()

forward

Given a successful Task, throw away the result and continue the chain with a new value. Useful for injecting singleton or constant values in place of null/void success values.

const task: Task<never, string> = Task.of(5).forward(() => "Hello")

append

Given a successful Task, join it before an additional value. Useful for threading a value along with a task. Like zip, but when one of the values is not a Task.

const task: Task<never, [number, number]> = Task.of(5).append(10)

prepend

Given a successful Task, join it after an additional value. Useful for threading a value along with a task. Like zip, but when one of the values is not a Task.

const task: Task<never, [number, number]> = Task.of(5).prepend(10)

ap

The applicative. If you know what that means, you'll be excited. If not, it is fine. This is a low level tool that helps build more complex features.

ap starts with a Task which succeeds containing a function. Subsequence chains of ap will each provide a task. The success of all those tasks will be given to the initial task which resulted in a function. This is a type safe way of running map on an arbitrary number of tasks. The function specifies its arguments, which must equal the number of ap chains. Similar to Task.all, but with 1 parameter per task, rather than an array, and it works with different task success types, rather than requiring all tasks succeed with the same type.

Also allows the definition of the mapping function to be asychronous because it is also inside a Task.

const task: Task<never, number> = Task.of((a, b, c) => a + b + c)
  .ap(succeed(10)) // a
  .ap(succeed(50)) // b
  .ap(succeed(100)) // c

Last updated