Skip to main content

Use async and await judiciously

Async functions are a powerful feature in JavaScript and TypeScript, offering a cleaner, more readable alternative to working directly with Promises. However, it’s easy to overuse them or add unnecessary layers of complexity.  By understanding when and how to use async and await effectively, you can write more concise, efficient, and maintainable code.

Let’s explore a common scenario where async and await may be overapplied, and how simplifying the function structure can improve code readability and maintainability without sacrificing intent. Take a look at this function which wraps an async function which deletes an entity form a database:

const deleteEntity = async (id: number) => {
    return await db.entity.delete({ id });
}


You would also await deleteEntity when calling it, resulting in two promises, unnecessarily verbose code and less efficient execution.. Instead of awaiting the promise created in deleteEntity, it can just be returned:

const deleteEntity = async (id: number) => {
    return db.entity.delete({ id });
}


Although async functions can contain zero or more awaits, it doesn’t really make much sense having async if you have zero awaits and it certainly isn’t necessary:

const deleteEntity = (id: number) => {
    return db.entity.delete({ id });
}

async can be a useful indicator that a function should be awaited, all async functions return a promise. However, I prefer to indicate this by specifying the return type:

const deleteEntity = (id: number) : Promise<void> => {
    return db.entity.delete({ id });
}


It may come down to style, but at this point the deleteEntity function body isn’t required either:

const deleteEntity = (id: number) : Promise<void> => db.entity.delete({ id });

This way you can have much simpler code, which can be considered easier to maintain while maintaining the intent and identical functionality.

Async functions are a valuable tool for simplifying asynchronous code in JavaScript and TypeScript, but using them unnecessarily can lead to bloated and inefficient code. A common pitfall is wrapping Promises in extra layers of async and await, resulting in redundant code without added benefit. By simply returning the Promise or specifying the return type, functions can be made more concise and readable without losing clarity or intent. Ultimately, understanding the behavior of async and await allows for better code decisions and improved maintainability.

Read more here.

Comments

Popular posts from this blog

Write Your Own Load Balancer: A worked Example

I was out walking with a techie friend of mine I’d not seen for a while and he asked me if I’d written anything recently. I hadn’t, other than an article on data sharing a few months before and I realised I was missing it. Well, not the writing itself, but the end result. In the last few weeks, another friend of mine, John Cricket , has been setting weekly code challenges via linkedin and his new website, https://codingchallenges.fyi/ . They were all quite interesting, but one in particular on writing load balancers appealed, so I thought I’d kill two birds with one stone and write up a worked example. You’ll find my worked example below. The challenge itself is italics and voice is that of John Crickets. The Coding Challenge https://codingchallenges.fyi/challenges/challenge-load-balancer/ Write Your Own Load Balancer This challenge is to build your own application layer load balancer. A load balancer sits in front of a group of servers and routes client requests across all of the serv...

Catalina-Ant for Tomcat 7

I recently upgraded from Tomcat 6 to Tomcat 7 and all of my Ant deployment scripts stopped working. I eventually worked out why and made the necessary changes, but there doesn’t seem to be a complete description of how to use Catalina-Ant for Tomcat 7 on the web so I thought I'd write one. To start with, make sure Tomcat manager is configured for use by Catalina-Ant. Make sure that manager-script is included in the roles for one of the users in TOMCAT_HOME/conf/tomcat-users.xml . For example: <tomcat-users> <user name="admin" password="s3cr£t" roles="manager-gui, manager-script "/> </tomcat-users> Catalina-Ant for Tomcat 6 was encapsulated within a single JAR file. Catalina-Ant for Tomcat 7 requires four JAR files. One from TOMCAT_HOME/bin : tomcat-juli.jar and three from TOMCAT_HOME/lib: catalina-ant.jar tomcat-coyote.jar tomcat-util.jar There are at least three ways of making the JARs available to Ant: Copy the JARs into th...

RESTful Behaviour Guide

I’ve used a lot of existing Representational State Transfer (REST) APIs and have created several of my own. I see a lot of inconsistency, not just between REST APIs but often within a single REST API. I think most developers understand, at a high level, what a REST API is for and how it should work, but lack a detailed understanding. I think the first thing they forget to consider is that REST APIs allow you to identify and manipulate resources on the web. Here I want to look briefly at what a REST API is and offer some advice on how to structure one, how it should behave and what should be considered when building it. I know this isn’t emacs vs vi, but it can be quite contentious. So, as  Barbossa from Pirates of the Caribbean said, this “...is more what you’d call ‘guidelines’ than actual rules.” Resources & Identifiers In their book, Rest in Practice - Hypermedia and Systems Architecture (‎ISBN: 978-0596805821), Jim Webber, Savas Parastatidis and Ian Robinson describe resour...