Async Await in JavaScript

Asynchronous programming is a crucial part of JavaScript, allowing developers to execute non-blocking code efficiently. Async/Await is a modern approach to handling asynchronous operations, making it easier to read and write compared to traditional callback-based or promise-based syntax.

What is Async/Await in JavaScript?

Async/Await is a syntactic feature in JavaScript introduced in ES2017 (ES8) to simplify working with Promises. It allows developers to write asynchronous code in a synchronous manner, improving readability and maintainability.

  • The async keyword is used to define an asynchronous function, which always returns a Promise.

  • The await keyword pauses the execution of the function until the Promise is resolved or rejected.

				
					async function fetchData() {
    let response = await fetch('https://jsonplaceholder.typicode.com/posts/1');
    let data = await response.json();
    console.log(data);
}
fetchData();
				
			

Error Handling in Async/Await

Handling errors in Async/Await can be done using the try...catch block. This provides a clean and efficient way to manage errors in asynchronous code.

				
					async function fetchData() {
    try {
        let response = await fetch('https://invalid-url.com');
        if (!response.ok) {
            throw new Error(`HTTP error! Status: ${response.status}`);
        }
        let data = await response.json();
        console.log(data);
    } catch (error) {
        console.error("Error fetching data:", error.message);
    }
}
fetchData();
				
			

Handling Promise Chain using Async/Await

Using Async/Await, we can handle a chain of Promises in a more structured way, avoiding callback hell and excessive .then() chaining.

				
					async function getUserData(userId) {
    try {
        let user = await fetch(`https://jsonplaceholder.typicode.com/users/${userId}`).then(res => res.json());
        let posts = await fetch(`https://jsonplaceholder.typicode.com/posts?userId=${userId}`).then(res => res.json());
        
        return { user, posts };
    } catch (error) {
        console.error("Error fetching user data:", error);
    }
}

getUserData(1).then(data => console.log(data));
				
			

Running Promises in Parallel using Async/Await

To execute multiple asynchronous operations in parallel, we can use Promise.all(), which runs multiple promises concurrently.

				
					async function fetchMultipleData() {
    try {
        let [users, posts] = await Promise.all([
            fetch('https://jsonplaceholder.typicode.com/users').then(res => res.json()),
            fetch('https://jsonplaceholder.typicode.com/posts').then(res => res.json())
        ]);
        console.log("Users:", users);
        console.log("Posts:", posts);
    } catch (error) {
        console.error("Error fetching data:", error);
    }
}
fetchMultipleData();
				
			

Async/Await provides a cleaner, more readable way to handle asynchronous code in JavaScript. It simplifies error handling and makes working with promises more intuitive. By leveraging try...catch for error handling, Promise.all() for parallel execution, and structured promise chaining, developers can write robust and maintainable asynchronous applications.