Try is a quasi monad that mimics the Promise API while handling synchronous and asynchronous code safely.
npm install @microlib/try
bun add @microlib/try
- Supports both synchronous and asynchronous execution.
- Mimics the
Promise
API (then
,catch
,finally
).
Synchronous Usage
import { Try } from "@microlib/try";
function task() {
if (Math.random() > 0.5) {
throw new Error("Something went wrong");
} else {
return "Hello";
}
}
// Try(task: syncfn) returns Success<T> | Failure (which is just like a Promise, but synchronous)
const result = Try(task)
.catch(() => "Bye")
.then((v) => v + ", World!");
if (result.ok) {
console.log(result.value);
}
/*
Output can be any of these:
- Hello, World!
- Bye, World!
*/
Asynchronous Usage
import { Try } from "@microlib/try";
async function task(): Promise<string> {
return new Promise((resolve, reject) =>
setTimeout(
() => (Math.random() > 0.5 ? resolve("Theo") : reject("Prime")),
100
)
);
}
// Try(task: asyncfn) returns a Promise
await Try(task)
.then((v) => console.log(`${v} uses VSCode`))
.catch((e) => console.log("NeoVim FTW"));
/*
Output can be any of these:
- Theo uses VSCode
- NeoVim FTW
*/
Give a โญ๏ธ if this project helped you!