Menu

How to write async await without try-catch blocks in Javascript

ES7 Async/await allows us as developers to write asynchronous JS code that look synchronous. In current JS version we we're introduced to Promises, that allows us to simplify our Async flow and avoid Callback-hell.

A callback-hell is a term used to describe the following situation in JS:

But in real world scenarios the async flow might get a little more complex, for instance in your server model (nodejs) you might want to save an entity to a database, then look for some other entity based on saved value, if that value exists do some other async task, after all tasks finished you might want to respond to the user with the created object from step 1. And if error occurred during one of the steps you want to inform the user with the exact error.

With promises of-course it would look much cleaner then with plain callbacks, but still, it can get a little messy IMHO.

ES7 Async/await

Note: You will need to use a transpiler in order to enjoy async/await, you can use either babel or typescript to the polyfills required.

That's where I find async await really useful, it allows you to write code like this:

When making async calls something may happen during the execution of the promise(DB connection error, db model validation error, etc..)

Since async functions are waiting for Promises, when a promise encounters an error it throws an exception that will be catched inside a catch method on the promise.

In async/await functions it is common to use try/catch blocks to catch such errors.

I'm not coming from a typed language background, so the try/catch adds for me additional code that in my opinion doesnt look that clean. I'm sure it's a matter of personal preference, but that's my opinion.

The example above is just a simple use-case for the solution, you can attach interceptor inside the to.js method which will receive the raw error object, log it or do whatever you need to do with it before passing it back.

There is a simple NPM package we created for this library, you can install it using: Github Repo

npm i await-to-js

This post is just a different way of looking on the async/await feature, it's totally based on personal opinion. You can achieve similar results using promises, single try-catch, and many other solutions. As long as you like something and it works for you stick with it :)