Turns a failure the caller is prepared to ignore into an undefined result, so the computation stays a single
expression instead of splitting into a try/catch statement. The result composes with opt, which maps it
or closes the failure case with a fallback, supplied either outright or computed only when the task fails.
Any other value is returned unchanged, null included. A task that returns undefined cannot be told apart from a
failed one, so absorbing failures suits only tasks whose successful results are always defined.
Important
Only synchronous failures are absorbed. A rejected promise returned by the task is passed on unchanged, and its
failure is to be handled with .catch() on the promise itself, or by awaiting it inside a try/catch statement.
The value returned by task, or undefined if task throws, whatever was thrown
Example
safe(() =>JSON.parse(text)); // parsed value or undefined (malformed text) opt(safe(() =>newURL(href)), url=>url.host, "localhost"); // string (the fallback if href is malformed)
Executes a task, absorbing its failures.
Turns a failure the caller is prepared to ignore into an
undefinedresult, so the computation stays a single expression instead of splitting into atry/catchstatement. The result composes with opt, which maps it or closes the failure case with a fallback, supplied either outright or computed only when the task fails.Any other value is returned unchanged,
nullincluded. A task that returnsundefinedcannot be told apart from a failed one, so absorbing failures suits only tasks whose successful results are always defined.Only synchronous failures are absorbed. A rejected promise returned by the task is passed on unchanged, and its failure is to be handled with
.catch()on the promise itself, or by awaiting it inside atry/catchstatement.