A function to wrap so it never throws an error or produces a
Promise
rejection.
Given a function which returns a Promise
and a function to transform thrown
errors or Promise
rejections resulting from calling that function, return a
new function with the same parameters but which returns a Task
.
To catch all errors but leave them unhandled and unknown
, see the other
overload.
This is basically just a convenience for something you could do yourself by
chaining safe
with Maybe.of
:
import Maybe from 'true-myth/maybe';
import { safe, safeNullable } from 'true-myth/task';
async function numberOrNull(value: number): Promise<number | null> {
return Math.random() > 0.5 ? value : null;
}
// Using this helper
const safeNumberOrNull = safeNullable(numberOrNull);
// Using `safe` and `Maybe.of` manually
const moreWorkThisWay= safe(numberOrNull);
let theTask = moreWorkThisWay(123).map((n) => Maybe.of(n));
The convenience is high, though, since you can now use this to create fully
safe abstractions to use throughout your codebase, rather than having to
remember to do the additional call to map
the Task
’s resolution value into
a Maybe
at each call site.
Given a function which returns a
Promise
of a nullable type, return a new function with the same parameters but which returns aTask
of aMaybe
instead.If you wish to transform the error directly, rather than with a combinator, see the other overload, which accepts an error handler.
This is basically just a convenience for something you could do yourself by chaining
safe
withMaybe.of
:The convenience is high, though, since you can now use this to create fully safe abstractions to use throughout your codebase, rather than having to remember to do the additional call to
map
theTask
’s resolution value into aMaybe
at each call site.