@microlib/try
TypeScript icon, indicating that this package has built-in type declarations

2.1.0 • Public • Published

📦 @microlib/try

npm version npm downloads Github Actions Bundlephobia

Try is a quasi monad that mimics the Promise API while handling synchronous and asynchronous code safely.

🚀 Installation

npm install @microlib/try
bun add @microlib/try

🔥 Features

  • Supports both synchronous and asynchronous execution.
  • Mimics the Promise API (then, catch, finally).

📖 Usage

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

*/

🍀 Show your Support

Give a ⭐️ if this project helped you!

Readme

Keywords

Package Sidebar

Install

npm i @microlib/try

Weekly Downloads

6

Version

2.1.0

License

none

Unpacked Size

16.7 kB

Total Files

13

Last publish

Collaborators

  • tanishqmanuja