JavaScript Async/Await: Writing Clean and Efficient Asynchronous Code

Harish Kumar · · 616 Views

JavaScript is a single-threaded programming language. Thus, it means that it can execute one command at a time. How can this be possible? Well, the answer lies in the fact that JavaScript has something called asynchronous programming. It enables the execution of other code in the program while waiting for the result of those long operations.

👉 Download Javascript: from ES2015 to ES2023 - eBook

Primer on async/await

Async/await is one of the modern ways to handle asynchronous operations in JavaScript. It gave developers, implemented in ECMAScript 2017, the possibility to realize asynchronous operations in such a way that they looked and felt a bit more synchronous—hence, readable and easier to maintain.

Key Concepts:

  1. Async function: A function declared via the async keyword; returns a Promise.

  2. Await Expression: Suspends execution of the async function and waits for the resolution or rejection of the Promise. It can only be used inside an async function.

Using async/await

Declaring an Async Function

An async function is declared using the async keyword before the declaration of the function:

async function fetchData() {
    // code
}

The Await Expression

The await keyword can be used to pause the execution of an async function until a Promise is resolved or rejected. It makes asynchronous code look synchronous:

async function fetchData() {
    const response = await fetch('https://api.example.com/data');
    const data = await response.json();
    console.log(data);
}

In this example, fetchData is an async function that fetches data from an API. The await fetch('https://api.example.com/data') pauses the function execution until the fetch promise is resolved. Similarly, await response.json() waits until the promise returned by response.json() is resolved.

Error Handling with async/await

Error handling with async/await can be done using try...catch blocks:

async function fetchData() {
    try {
        const response = await fetch('https://api.example.com/data');
        if (!response.ok) {
            throw new Error('Network response was not ok');
        }
        const data = await response.json();
        console.log(data);
    } catch (error) {
        console.error('There has been a problem with your fetch operation:', error);
    }
}

In this example, if any of the await expressions throw an error, it is caught in the catch block.

Advantages of async/await

  1. Readability: Code written with async/await is easier to read and understand.

  2. Debugging: Easier to debug than traditional promise chains.

  3. Error Handling: More straightforward error handling with try...catch.

Practical Example

Here’s a practical example of using async/await to fetch multiple resources:

async function fetchMultipleData() {
    try {
        const [response1, response2] = await Promise.all([
            fetch('https://api.example.com/data1'),
            fetch('https://api.example.com/data2')
        ]);
        
        const data1 = await response1.json();
        const data2 = await response2.json();
        
        console.log('Data 1:', data1);
        console.log('Data 2:', data2);
    } catch (error) {
        console.error('Error fetching data:', error);
    }
}

fetchMultipleData();

In this example, Promise.all is used to fetch multiple resources in parallel. The function waits for both fetch operations to complete before proceeding.

Conclusion

async/await provides a powerful way to work with asynchronous code in JavaScript, making it more readable and easier to manage. By using async functions and the await keyword, developers can write code that looks synchronous but works asynchronously, improving both the structure and maintainability of their code.

Summary

  1. async keyword is used to declare an async function.

  2. await keyword is used to wait for a promise to resolve.

  3. Error handling is done using try...catch blocks.

  4. Promise.all can be used to run multiple promises in parallel.

By understanding and using async/await, developers can write cleaner and more efficient asynchronous code in JavaScript.

👉 Download Javascript: from ES2015 to ES2023 - eBook

JavaScript Async/Await: Writing Clean and Efficient Asynchronous Code
0

Please login or create new account to add your comment.

0 comments
You may also like:

Understanding the `.reduce()` Method in JavaScript

The .reduce() method in JavaScript is one of the most powerful array methods used for iterating over array elements and accumulating a single value from them. Whether you're summing (...)
Harish Kumar

Building a Real-Time Chat App with Laravel Reverb and Nuxt 3

Building a real-time chat application is a great way to understand the power of WebSockets and real-time communication. In this tutorial, we will walk through creating a Real-Time (...)
Harish Kumar

How to Use JavaScript’s .every() and .some() for Smarter Array Handling

JavaScript provides a variety of array methods that allow developers to perform common tasks in an efficient, clean, and readable manner. Among these methods are .every() and .some(), (...)
Harish Kumar

How to Set Up Nuxt 3 Authentication with Laravel Sanctum (Step-by-Step Guide)

In modern web development, securing your application’s authentication process is a top priority. For developers building Single Page Applications (SPA) or Server-Side Rendered (...)
Harish Kumar

Understanding `.slice()` and `.splice()`: JavaScript Array Methods

In JavaScript, arrays come with numerous built-in methods for manipulation. Two commonly used methods are .slice() and .splice(). While they sound similar, their purposes and behaviors (...)
Harish Kumar

Vue 3.5 Release: What's New and Improved?

Vue.js has released version 3.5, bringing a host of exciting new features and optimizations designed to boost developer productivity and improve application performance. This update (...)
Harish Kumar