JavaScript Async/Await: Writing Clean and Efficient Asynchronous Code

Harish Kumar · · 737 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:

15 Must-Know TypeScript Features to Level Up Your Development Skills

TypeScript has become the go-to tool for developers building scalable, maintainable JavaScript applications. Its advanced features go far beyond basic typing, giving developers (...)
Harish Kumar

JavaScript Best Practices: Tips for Writing Clean and Maintainable Code

JavaScript is one of the most versatile and widely used programming languages today, powering everything from simple scripts to complex web applications. As the language continues (...)
Harish Kumar

Ditch jQuery: Vanilla JS Alternatives You Need to Know

jQuery revolutionized web development by simplifying DOM manipulation, event handling, and animations. However, modern JavaScript (ES6 and beyond) now provides many built-in methods (...)
Harish Kumar

Shallow Copy vs Deep Copy in JavaScript: Key Differences Explained

When working with objects and arrays in JavaScript, it's crucial to understand the difference between shallow copy and deep copy. These concepts dictate how data is duplicated (...)
Harish Kumar

A Beginner’s Guide to Efficient Memory Use in JavaScript

Managing memory efficiently in JavaScript applications is essential for smooth performance, especially for large-scale or complex applications. Poor memory handling can lead to (...)
Harish Kumar

Exploring the New Features of JavaScript ES2024: A Look into the Future of Web Development

Discovering new functionality in programming languages is a bit like a holiday — it’s filled with anticipation and the excitement of exploring something new. With the proposed (...)
Harish Kumar