Utils functions to use with Task.
caseError function is used to handle errors of an specific type (instance of the specified Error) with a callback.
import { Task } from '@acamica/task';
import { caseError } from 'ts-task-utils';
// rejectedTask is a Task<never, FooError | BarError>
const rejectedTask = Task.reject(
Math.random() > 0.5 ?
new FooError() :
new BarError()
);
rejectedTask
.catch(err =>
// err is FooError | BarError
Task.reject(err)
)
.catch(caseError(FooError, err =>
// err is a FooError
Task.resolve('foo ' + err.toString()))
)
.catch(err =>
// err is a BarError (since the FooError case was resolved)
Task.reject(err)
)
;Note: have in mind that TypeScript does duck typing checks, hence
FooErrorandBarErrorshould have different properties to let TypeScript infere they are different.
toPromise function naturally transforms a Task into a Promise.
import { Task } from '@acamica/task';
import { toPromise } from 'ts-task-utils';
// resolvedTask is a Task<number, never>
const resolvedTask = Task.resolve(9);
// resolvedPromise is Promise<number>
const resolvedPromise = toPromise(resolvedTask);
// rejectedTask is a Task<never, Error>
const rejectedTask = Task.resolve(new Error());
// rejectedPromise is Promise<never>, rejected with Error
const rejectedPromise = toPromise(rejectedTask);As Tasks are lazy, the Task's code isn't executed until it's resolved. But, for the same reason the Task's code is executed each time it is forked (operators - including .map, .chain and .catch methods - do fork the Task). share function is an operator that resolves the Task to that point and returns a Task resolved (or rejected) with that value, so original Task's code is executed only once.
import { Task } from '@acamica/task';
import { share } from 'ts-task-utils';
const task = new Task<string, never>(resolve => {
console.log('Task\'s code is called');
resolve('Foo');
});
const sharedTask = task
.pipe(share);
sharedTask.fork(err => console.log(err), val => console.log(val));
sharedTask.fork(err => console.log(err), val => console.log(val));
sharedTask.fork(err => console.log(err), val => console.log(val));
// The message "Task's code is called" will be logged only once (even when forking multiple times).Gonzalo Gluzman 💻 📖 |
Hernan Rajchert 💻 🎨 📖 🤔 |
|---|
This project follows the all-contributors specification. Contributions of any kind are welcome!