0.2.0 • Published 6 years ago
can-error v0.2.0
Can-Error
canError is a higher-order function, that wraps another function to yield errors and results on the same scope.
This is useful if you want to keep variables within the same block-scope to avoid variable reassignment (i.e. using let
).
Inspired by
This package is inspired by the following packages.
What this package does differently though, is: when a non-async function is wrapped, the resultant function does not need to be awaited (this also works in TypeScript).
The problem with await-to-js
and try-to-catch
is that anytime those functional try-catch wrappers are used (especially on synchronous functions), async
starts spreading throughout the codebase unnecessarily.
Usage
import canError from "can-error";
// You can also use a named import
// import { canError } from "canError";
const asyncFunc = async () => {
const [err, result] = await canError(Model.findOne)({ id: "value" });
return (err)
? // handle err
: result;
}
// This does not need to be awaited.
const syncFunc = () => {
const [err, result] = canError((str: string) => str)("value");
return (err)
? // handle err
: result;
};