npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

tryio

v1.0.0

Published

A robust async helper to wrap promises and functions, returning [result, error] for graceful error handling.

Readme

tryio

npm version License: MIT

tryio is a helpful tool for handling errors in your code. It wraps your functions and promises, allowing you to easily manage errors without the need for repetitive try...catch blocks. With tryio, you get a simple way to work with async code while keeping it clean and easy to read based off of trysafely.

How to Use

tryio provides three main ways to handle your operations:

  1. Using tryAsync(fn: () => Promise<T>): This wraps a function that returns a promise. It catches any errors that happen when the function runs.
  2. Using tryPromise(promise: Promise<T>): This wraps an already-created promise, which is useful when the promise is already running.
  3. Using trySync(fn: () => T): This wraps a synchronous function and catches any errors that occur during its execution.

Basic Example with tryAsync

Wrap your async function in tryAsync to get a [data, error] pair. This is great for deferring the execution of your async operation.

import { tryAsync } from 'tryio';

// Function to fetch user details
async function fetchUserDetails(userId: string): Promise<{ id: string; name: string }> {
  await new Promise(resolve => setTimeout(resolve, 100));

  if (userId === "user123") {
    return { id: "user123", name: "Alice" };
  } else if (userId === "errorUser") {
    throw new Error("Network error during fetch!");
  } else {
    throw "Invalid User ID format.";
  }
}

async function getUser() {
  const [user, err] = await tryAsync(() => fetchUserDetails("user123"));

  if (err) {
    console.error("Failed to get user:", err.message);
  } else {
    console.log("User data:", user);
  }

  const [errorUser, errorErr] = await tryAsync(() => fetchUserDetails("errorUser"));

  if (errorErr) {
    console.error("Failed to get error user:", errorErr.message);
  }

  const [unknownUser, unknownErr] = await tryAsync(() => fetchUserDetails("unknownUser"));

  if (unknownErr) {
    console.error("Failed to get unknown user:", unknownErr.message);
  }
}

getUser();

Example with tryPromise

If you already have a promise, you can use tryPromise to wrap it directly.

import { tryAsync, tryPromise } from 'tryio';

async function fetchConfig(): Promise<{ theme: string; debug: boolean }> {
  await new Promise(resolve => setTimeout(resolve, 50));
  return { theme: "dark", debug: false };
}

async function retrieveData() {
  const [config, configErr] = await tryPromise(fetchConfig());

  if (configErr) {
    console.error("Failed to fetch config:", configErr.message);
  } else {
    console.log("Config loaded:", config);
  }
}

retrieveData();

Example with trySync

For synchronous operations, you can use trySync to handle errors without needing a try...catch block.

import { trySync } from 'tryio';

// Function to parse a JSON string
function parseJson(jsonString: string): object {
  return JSON.parse(jsonString);
}

const [data, parseError] = trySync(() => parseJson('{"key": "value"}'));

if (parseError) {
  console.error("Failed to parse JSON:", parseError.message);
} else {
  console.log("Parsed data:", data);
}

Using with Promise.all

tryAsync and tryPromise work well together when you need to handle multiple async operations at once.

import { tryAsync, tryPromise } from 'tryio';

async function loadDashboard() {
  const [salesResult, inventoryResult, analyticsResult] = await Promise.all([
    tryAsync(() => fetchSalesData()),
    tryPromise(fetchInventoryData()),
    tryAsync(() => fetchAnalyticsSummary()),
  ]);

  // Handle results...
}

loadDashboard();

Key Features

  • No More Boilerplate: Say goodbye to long try...catch blocks. Use tryio to handle errors in a single line.
  • Clear Error Handling: Always get a [result, error] pair, making it easy to check for errors.
  • Handles Both Async and Sync Errors: Works for both promise rejections and errors thrown during function execution.
  • TypeScript Support: Fully typed for a better coding experience and safety.
  • Lightweight: Minimal overhead, focusing on simplifying async error handling.
  • Three Ways to Use: You can wrap a function that returns a promise, directly wrap an existing promise, or handle synchronous functions.

Installation

To install tryio, run one of the following commands:

npm install tryio
# or
yarn add tryio
# or
pnpm add tryio

Why Choose tryio?

Using tryio makes your code easier to read and maintain. Instead of dealing with complex error handling, you can focus on what your code does. It helps you see where errors happen and keeps your async code clean and predictable.

When to Use trysafely Instead

While tryio provides a simple and clean error handling approach, if you need stricter TypeScript typing where successful results aren't marked as possibly null after error checking, consider using trysafely. It offers a more type-strict implementation that can provide better compile-time guarantees for your error handling patterns.

Contributing

We welcome contributions! If you have ideas, bug reports, or want to help with code, please open an issue or pull request on the GitHub repository.

License

tryio is MIT licensed.