Git Product home page Git Product logo

try's Introduction

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.

try's People

Contributors

bdsqqq avatar kduprey avatar krowter avatar nicolaslopes7 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar

try's Issues

Alternative API

I'm glad someone released a library like this, I've been using this pattern for quite some time now, it rocks!

This issue is only a suggestion for what could be, perhaps, an alternative export with a different return signature

import { $try } from '@bdsqqq/try'

const promise = () => 
  new Promise((res) => 
    setTimeout(() => res('aha!'), 1000)
  )

const promiseThatRejects = () => 
  new Promise((_, rej) => 
    setTimeout(() => rej(new Error('oh no')), 1000)
  )

const result = await $try(promise())
if (!result.error) console.log(result.data)

const otherResult = await $try(promiseThatRejects())
if (!otherResult.error) console.log(otherResult.data)

This allows for better naming through not repeating yourself, sometimes

const fetched = await $try(fetchItems())
if (fetched.error) return handleError(fetched.error)

const transformed = await $try(transform(fetched.data))
if (transformed.error) return handleError(transformed.error)

Is less repetitive to write than

const [fetched, fetchedError] = await $try(fetchItems())
if (fetchedError) return handleError(fetchedError)

const [transformed, transformedError] = await $try(transform(fetched.data))
if (transformedError) return handleError(transformedError)

There is an argument about semantics and line width here as well, but I'm way too hungover to remember

Fix Spelling on License File

The License file is not being picked up by GitHub or NPM due to the misspelling of the file in the root of the repo.

Package types are wrong

Hi, first thanks for making this!

I just tried it but it seems the types that are transpiled in the packags look like this:

declare const trytm: <T>(
   promise: Promise<T>,
) => Promise<readonly [Awaited<T>, null] | readonly [null, unknown]>;

export { trytm };

And the part that breaks is the | readonly [null, unknown]>

Because now if I try to use the package

const [data, error] = await trytm(myPromise())

error is unknown so even if I check if error !== null afterwards, the data type is not narrowed to not be null.

When copy/pasting the source in a helper directly in project it works alright.

data is possibly null

after handling the error and we are sure that the data is not null anymore, typescript cannot detect this and considers the data nullable. ts is still thinking about [null, error]

I was curious if it could be fixed though it is a typescript limit

const fetchData = () => Promise.resolve({id: 1})
const [data, error] = await trytm(fetchData())
if (error) {
  return
}

data.id // data is possibly null 

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.