Async/Await in JavaScript: Simplifying Asynchronous Code

Aquib Afzal
Bits and Pieces
Published in
6 min readFeb 26, 2023

--

Waiting
Photo by Matthew Henry on Unsplash

Async/await is a feature of JavaScript that simplifies asynchronous programming. We will define async/await, describe how it functions, and give some practical examples in this blog article.

Understand Asynchronous Programming

Asynchronous programming is a programming pattern where tasks are completed simultaneously and the results are returned as soon as they are ready. Traditional synchronous programming executes tasks sequentially, which might cause the user to wait a very long time.
Javascript offers asynchronous programming in primarily three different ways: callbacks, promises, and async/await.
Callbacks are functions that are executed after a task is completed and are passed as arguments in other functions. Promises are objects that stand in for values that might not be available right away but will be fulfilled eventually. Async/await is a modern method for managing asynchronous programming that makes the code syntax simpler and more readable.

I recommend to read JavaScript Promise before delving into Async/await for a better understanding of the underlying concepts.

What is Async/Await?

Programmers can write asynchronous code more synchronously using JavaScript’s async/await syntax feature. It is based on Promise and offers a cleaner, more legible approach to construct asynchronous programmes.

When a function is marked with the “async” prefix, it means that it will always return a Promise. The “await” keyword is used to halt the execution of the programme inside an async function until the Promise is fulfilled.

How to use Async/Await?

How to use Async/Await
Photo by Levi Meir Clancy on Unsplash

let’s look at an example to understand working of async/await. Consider the case where a function returns a Promise that resolves after some time:

function wait(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}

We can use this function to create a delay in our code. For instance, We can delay the execution of the function by one second by using the code below:

async function delayedFunction() {
await wait(1000);
console.log("Delayed function executed");
}

In this code, we have marked the “delayedFunction” as asynchronous using the “async” keyword. We have also used the “await” keyword to pause the execution of the code until the Promise returned by “wait” function is resolved. Once the Promise is resolved, the console will log the message “Delayed function executed”.

Handling Errors with Async/Await

Error Handling in JavaScript (Async/Await)
Photo by Sarah Kilian on Unsplash

Error handling is simplified when async/await is used, which is one of its advantages. We can use the “try/catch” to handle the error in a more synchronous way. For instance, that we have a function that returns a Promise which expires after some time:

function waitAndReject(ms) {
return new Promise((resolve, reject) => setTimeout(() => reject("Error"), ms));
}

We can use this function to simulate an error in our code. For example, we can handle the error in the following way:

async function errorFunction() {
try {
await waitAndReject(1000);
} catch (e) {
console.log(e);
}
}

In this code, we have used the “try/catch” statement to handle the error thrown by the Promise returned by “waitAndReject”. If the Promise is rejected, the error message “Error” will be logged to the console.

Real-world Examples of Async/Await

Real-world Examples of Async/Await
Photo by Anne Nygård on Unsplash

Let’s take a look at how to use async/await with the Fetch API to retrieve data from a third-party API:

async function getJokes(category) {
try {
const response = await fetch(`https://api.chucknorris.io/jokes/random?category=${category}`);
const data = await response.json();
const joke = data.value;
console.log(`Here's a joke about ${category}: ${joke}`);
} catch (e) {
console.log(`Error: ${e}`);
}
}

In this code, we have used async/await with the Fetch API to make an HTTP request to the Chuck Norris Jokes API and retrieve a random joke for a given category. We have also used try/catch to handle any errors that may occur during the request.

The Chuck Norris Jokes API is a public API that provides random jokes about Chuck Norris in different categories such as “dev”, “science”, “movie”, etc. This example demonstrates how to use async/await to retrieve data from a third-party API and use it in your application.

Benefits of Using Async/Await

why?
Photo by Emily Morter on Unsplash

Using async/await has several benefits over traditional asynchronous programming methods. First, it simplifies the syntax and makes the code more readable by avoiding callback nesting and chaining. Second, it allows for better error handling by using try/catch blocks to handle exceptions. Finally, it improves the performance of web applications by allowing tasks to execute concurrently and reducing the wait time for the user.

Best Practices for Using Async/Await

Photo by Austin Chan on Unsplash

While async/await provides a simpler and more concise way to write asynchronous code, there are still some best practices to keep in mind. Here are a few tips to help you write efficient and maintainable async/await code:

  1. Always use try/catch blocks to handle exceptions and errors.
  2. Use Promise.all() method to execute multiple asynchronous tasks concurrently.
  3. Use Promise.race() method to execute multiple asynchronous tasks and return the result of the first task that resolves or rejects.
  4. Avoid using await inside loops, as it can block the execution of other tasks.
  5. Use third-party libraries such as async or bluebird to handle complex asynchronous tasks.

In conclusion, JavaScript’s async/await functionality is a potent tool that lets programmers write asynchronous code in a more synchronous manner. It makes handling Promise easier and makes handling errors simpler. It could take some time to become used to the syntax and comprehend how async/await functions if you are a beginner. But once you get the hang of it, you’ll discover that writing asynchronous JavaScript code gets much simpler and more pleasurable.

Build Apps with reusable components, just like Lego

Bit’s open-source tool help 250,000+ devs to build apps with components.

Turn any UI, feature, or page into a reusable component — and share it across your applications. It’s easier to collaborate and build faster.

Learn more

Split apps into components to make app development easier, and enjoy the best experience for the workflows you want:

Micro-Frontends

Design System

Code-Sharing and reuse

Monorepo

--

--

Software Developer @ Encora Inc. | Blogger | talks about #javascript #react #nodejs #performance #webdevelopment