No more try...catch

July 28, 2020

Are you a back-end developer, handling multiple database operations & tasks or having custom promises written or has a service which returns a promise, and you have to handle it using the ugly try..catch block which might have one block containing several lines of code ? 🤔

Solution

There is a npm module available which reduces complexity and introduces better readability just as if it’s all synchronous in nature. It’s called await-to-js.

It’s an async await wrapper which focuses on making the task of error handling easier. The output from the function is a de-structured output with error and data, which can be further used independently.

Usage

const to = require("await-to-js").default

const getNotificationToken = async userId => {
  const [err, token] = await to(redis.get(userId))

  if (err) {
    // Handle your error
  }

  return token
}

a simple function which returns a token from redis for a particular user.

Thoughts

One should think & consider this to get started with less bugs while handling promises.


Profile picture

Written by Idrees Dargahwala who is a Software Engineer building useful things on the web. You should follow him on Twitter

githublinkedintwitter