Skip to content

microlib-js/try

Folders and files

NameName
Last commit message
Last commit date

Latest commit

ย 

History

40 Commits
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 

Repository files navigation

๐Ÿ“ฆ @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!