True Myth / task / TaskConstructor
Interface: TaskConstructor
The public interface for the Task class as a value: a constructor and the associated static properties.
Constructors
Constructor
new TaskConstructor<
T,E>(executor):Task<T,E>
Construct a new Task, using callbacks to wrap APIs which do not natively provide a Promise.
This is identical to the Promise constructor, with one very important difference: rather than producing a value upon resolution and throwing an exception when a rejection occurs like Promise, a Task always “succeeds” in producing a usable value, just like Result for synchronous code.
For constructing a Task from an existing Promise, see:
For constructing a Task immediately resolved or rejected with given values, see Task.resolve and Task.reject respectively.
Parameters
executor
(resolve, reject) => void
A function which the constructor will execute to manage the lifecycle of the Task. The executor in turn has two functions as parameters: one to call on resolution, the other on rejection.
Returns
Task<T, E>
reject()
Call Signature
Construct a Task which is already rejected. Useful when you have an error already, but need it to be available in an API which expects a Task.
Type Parameters
T
T = never
E
E extends object = { }
Returns
Call Signature
reject<
T,E>(reason):Task<T,E>
Construct a Task which is already rejected. Useful when you have an error already, but need it to be available in an API which expects a Task.
Type Parameters
T
T = never
E
E = unknown
Parameters
reason
E
Returns
Task<T, E>
resolve()
Call Signature
Construct a Task which is already resolved. Useful when you have a value already, but need it to be available in an API which expects a Task.
Type Parameters
T
T extends Unit
E
E = never
Returns
Call Signature
resolve<
T,E>(value):Task<T,E>
Construct a Task which is already resolved. Useful when you have a value already, but need it to be available in an API which expects a Task.
Type Parameters
T
T
E
E = never
Parameters
value
T
Returns
Task<T, E>
withResolvers()
withResolvers<
T,E>():WithResolvers<T,E>
Create a pending Task and supply resolveWith and rejectWith helpers, similar to the Promise.withResolvers static method, but producing a Task with the usual safety guarantees.
Examples
Resolution
let { task, resolveWith, rejectWith } = Task.withResolvers<string, Error>();
resolveWith("Hello!");
let result = await task.map((s) => s.length);
let length = result.unwrapOr(0);
console.log(length); // 5Rejection
let { task, resolveWith, rejectWith } = Task.withResolvers<string, Error>();
rejectWith(new Error("oh teh noes!"));
let result = await task.mapRejection((s) => s.length);
let errLength = result.isErr ? result.error : 0;
console.log(errLength); // 5Type Parameters
T
T
E
E
Returns
WithResolvers<T, E>