• Stars
    star
    225
  • Rank 177,187 (Top 4 %)
  • Language
    TypeScript
  • License
    MIT License
  • Created almost 2 years ago
  • Updated about 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Don't let the Try Catch Tower of Terror destroy your beautiful one liners.

Tryâ„¢

Don't let the Try Catch Tower of Terror destroy your beautiful one liners.

Usage

npm install @bdsqqq/try
import { trytm } from "@bdsqqq/try";

const mockPromise = () => {
  return new Promise<string>((resolve, _) => {
    setTimeout(() => {
      resolve("hello from promise");
    }, 1000);
  });
};

const mockPromiseThatFails = () => {
  return new Promise<string>((_, reject) => {
    setTimeout(() => {
      reject(new Error("hello from promise"));
    }, 1000);
  });
};

const [data, error] = await trytm(mockPromise());
const [data2, error2] = await trytm(mockPromiseThatFails());

Why does this exist?

Async await feels like heaven because it avoids the callback hell or Pyramid of Doom by writing asyncronous code in a line by line format:

function hell() {
   step1((a) => {
      step2((b) => {
         step3((c) => {
            // ...
         })
      })
   })
}

async function heaven(){
   const a = await step1();
   const b = await step2(a);
   const c = await step3(b);
   // ...
}

Until error handling comes into play... Because then you end up with the Try-Catch Tower of Terror, where your beautiful one-liners magically expand to at least 5 lines of code:

async function Terror(){
   let a;
   let b;
   let c;

   try {
      a = await step1();
   } catch (error) {
      handle(error);
   }


   try {
      b = await step2(a);
   } catch (error) {
      handle(error);
   }


   try {
      c = await step3(b);
   } catch (error) {
      handle(error);
   }

   // ...
}

An easy solution would be to append the .catch() method to the end of each promise:

async function easy(){
   const a = await step1().catch(err => handle(err));
   const b = await step2(a).catch(err => handle(err));
   const c = await step3(b).catch(err => handle(err));
   // ...
}

This approach solves the issue but can get a bit repetitive, another approach is to create a function that implements one Try Catch to replace all the others:

import { trytm } from "@bdsqqq/try"

async function awesome() {
   const [aData, aError] = await trytm(step1());
   if(aError) // ...

   const [bData, bError] = await trytm(step2(aData));
   if(bError) // ...

   const [cData, cError] = await trytm(step3(bData));
   if(cError) // ...

   // ...
}

Why does this REALLY exist?

I watched a fireship short and ended up in a rabbit hole to learn how to publish a NPM package. This is still an interesting pattern to use in your codebase but might be best copy pasted instead of being a dependency.

I'll leave the source code here so you don't have to look for the one .ts file in the /src folder:

export const trytm = async <T>(
   promise: Promise<T>,
): Promise<[T, null] | [null, Error]> => {
   try {
      const data = await promise;
      return [data, null];
   } catch (throwable) {
      if (throwable instanceof Error) return [null, throwable];

      throw throwable;
   }
};

Attributions

This code is blatantly stolen from a fireship youtube short, with minor additions to make data infer its typing from the promise passed as an argument.

More Repositories

1

igorbedesqui.com

My personal website and glorified playground. Watch as I overengineer the shit out of this to learn new stuff and explore tech I find interesting.
TypeScript
60
star
2

psykip

The best way to read The Enchiridion from Epictetus — We compiled translations from different authors at different points of history alongside the original Enchiridion to make sure you can read your favorite version of it.
Astro
46
star
3

warp-term-vesper-theme

24
star
4

things

Things, not many, mostly libraries.
Astro
22
star
5

spicetify-vesper-theme

Orange flavored dark theme for Spotify.
CSS
6
star
6

try-website

Minimal, yet overengineered, site for the @bdsqqq/try library.
Astro
5
star
7

better-discord-vesper-theme

Orange flavored Discord theme
CSS
5
star
8

next-wasm-gif

A website that helps you convert videos into gifs without sending any data anywhere.
TypeScript
4
star
9

bebop-webjam

A poster-like website that tries to convey the feeling of the tv show cowboy bebop. — My entry for (and winner of) the second installment of the WebJam.
HTML
4
star
10

vesper-zed

Peppermint and orange flavored dark theme for Zed.
4
star
11

typing-animation

TypeScript
3
star
12

iss-asset

A website that shows you the current location of the International Space Station.
TypeScript
3
star
13

haxiom

TypeScript
1
star
14

vite-vanillajs-tailwindcss

Template for vite projects with vanilla js with tailwindcss already installed
JavaScript
1
star
15

covid19-tracker

A webapp made to track and visualize data related to the Coronavirus Disease (COVID-19)
JavaScript
1
star
16

multi-user-todo

Esse é um projeto criado para a avaliação técnica de Igor Bedesqui.
TypeScript
1
star
17

tic-tac-two

The greatest sequel know to mankind, tic-tac-two improves on all aspects of the classic game of tic-tac-toe. Implemented perfectly 100% bug-free
TypeScript
1
star
18

contact-list-thing

TypeScript
1
star
19

react-wherestheiss

A react WebApp that tracks the ISS using an API
JavaScript
1
star
20

hex-to-hsl

TypeScript
1
star
21

carbon-layering-model-css

TypeScript
1
star