How to Avoid Async Try-Catch Hell

This post is based on this excellent short youtube video..

Let’s see async try-catch hell. If we do try-catch on every single async function, it creates a tower of terror. Welcome to try-catch hell.

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

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

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

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

There are two ways we can avoid this.

First of all, we can just catch the error by chaining it.

async function useCatch() {
  const a = await step1().catch(e => handle(e));
  const b = await step1().catch(e => handle(e));
  const c = await step1().catch(e => handle(e));

  return a + b + c;
}

Alternatively, in the async function we use, we can return an array of data and error.

async function handleTryCatch() {
  try {
    const data = await promise;
    return [data, null];
  } catch (e) {
    console.error(e);
    return [null, e];
  }
}

async function handleTryCatch2() {
  try {
    const data = await promise;
    return [data, null];
  } catch (e) {
    console.error(e);
    return [null, e];
  }
}

async function main() {
  const [data, error] = await handleTryCatch();

  if (error) {
    // can do action here.
  }

  const [data2, error2] = await handleTryCatch2();
  const [data3, error3] = await handleTryCatch3();
}

Amazing!

Front-End
TypeScript: type aliases to check type equality

This post is to analyse how the type equality check by using type aliases proposed by Matt Pocock in his twitter post. These type aliases allow us to elegantly express type equality checks in unit tests. All we need to do is to pass the output and expected types in …

Front-End
Fixing it.only type error in Jest

If you are getting a type error with it.only in Jest, it could be due to incorrect TypeScript typings or incompatible versions of Jest and TypeScript. To resolve this issue, you can try the following steps: Make sure you have the latest versions of Jest and its TypeScript typings installed …

Front-End
yup conditional validation example

Here’s an example of a Yup validation logic where the first input field is optional but, if filled, it must contain only alphabetic characters, and the second input field is required: import * as Yup from “yup”; const validationSchema = Yup.object().shape({ firstField: Yup.string().matches(/^[A-Za-z]*$/, { message: “First field must contain only …