2.1.0 • Published 8 months ago

@microlib/try v2.1.0

Weekly downloads
-
License
-
Repository
github
Last release
8 months ago

📦 @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!

2.0.5

12 months ago

2.0.7

12 months ago

2.0.6

12 months ago

2.1.0

8 months ago

2.0.3

1 year ago

2.0.2

1 year ago

2.0.4

1 year ago

2.0.1

1 year ago

2.0.0

1 year ago

1.0.0

1 year ago