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 🙏

© 2024 – Pkg Stats / Ryan Hefner

ts-safe-promise

v1.0.2

Published

A lightweight utility to handle promises safely, returning an error or result in a predictable format.

Downloads

216

Readme

ts-safe-promise

Downloads Version

A lightweight utility for handling promises safely without the need for try...catch. This package returns both error and result in a predictable format, simplifying asynchronous error handling in JavaScript and TypeScript.

Installation

npm install ts-safe-promise

Or with yarn:

yarn add ts-safe-promise

Example

  • Import safePromise and use it to handle async functions without try...catch:
import { safePromise } from 'ts-safe-promise';

async function fetchData() {
	const [error, data] = await safePromise(fetchDataFromAPI());

	if (error) {
		console.error('Error fetching data:', error);
		return;
	}

	console.log('Data:', data);
}

Why ts-safe-promise?

In JavaScript, handling asynchronous operations often involves using try...catch blocks around await statements. While effective, this approach has a few downsides:

  1. Verbosity: Every time you need to handle errors, you end up writing try...catch around each async function, making code longer and less readable.
  2. Nested Error Handling: When chaining multiple promises, try...catch becomes cumbersome and may lead to nested error handling.
  3. Inconsistent Results: Without try...catch, an unhandled promise rejection can crash your application, making it necessary to handle errors carefully in every async call.

Example Problem

Using try...catch repeatedly can clutter your code:

async function fetchData() {
	try {
		const data = await fetchDataFromAPI();
		return data;
	} catch (error) {
		console.error('Error fetching data:', error);
		return null;
	}
}

With multiple await statements, this can get repetitive and harder to read:

async function performActions() {
	try {
		const data1 = await fetchDataFromAPI1();
		const data2 = await fetchDataFromAPI2(data1);
		const result = await processData(data2);
		return result;
	} catch (error) {
		console.error('Error performing actions:', error);
	}
}

How ts-safe-promise Solves This

  • ts-safe-promise offers a simpler way to handle asynchronous operations by ensuring every Promise returns in a consistent [error, data] format:

  • Consistent Results: Each async function call always returns either [undefined, result] (on success) or [error, undefined] (on failure).

  • Readable Code: Avoids try...catch, allowing for more readable and maintainable code. Flexible Error Handling: Handle errors directly in the response without needing to wrap each call.

Usage

import { safePromise } from 'ts-safe-promise';

async function performActions() {
	const [error1, data1] = await safePromise(fetchDataFromAPI_1());
	if (error1) {
		console.error('Error fetching data 1:', error1);
		return;
	}

	const [error2, data2] = await safePromise(fetchDataFromAPI_2(data1));
	if (error2) {
		console.error('Error fetching data 2:', error2);
		return;
	}

	const [error3, result] = await safePromise(processData(data2));
	if (error3) {
		console.error('Error processing data:', error3);
		return;
	}

	console.log('Result:', result);
}

API

  • safePromise(promise: Promise): Promise<[Error, undefined] | [undefined, T]>
  • Parameters: Accepts a promise that resolves with type T.
  • Returns: A promise resolving to [undefined, result] if successful, or [error, undefined] if failed.

License

MIT License.