JavaScript Async/Await

Introduction

In this tutorial, you will learn the concept of JavaScript Async/Await

Async/Await is used to handle asynchronous operations such as API requests, file loading, or database queries.

Developers used callbacks and later Promises, and now using Async/Await approach.

What is Async/Await in JavaScript?

Async/Await is a modern syntax in JavaScript used to handle asynchronous code.

It is built on top of JavaScript Promises, but it looks similar to synchronous code.

Important Things:

  1. async makes a function return a Promise.
  2.  await pauses execution until the Promise resolves.

Why Async/Await is Important

Initially, developers used Callback Functions and Promises, and now use Async/Await.

What are the problems with older methods?

There are some problems when we use older methods.

  1. Callback Hell.
  2. It is very difficult to handle error handling.
  3. It is very Hard to read code.

Note: Async/Await solves these issues by making asynchronous code look like normal sequential code.

Basic Syntax


async function getData() {
  let response = await fetch("https://api.example.com/data");
  let data = await response.json();
  console.log(data);
}
getData();

Explanation:

  1. async → declares an asynchronous function.
  2. await → waits for the Promise to resolve.
  3. Code runs in a top-to-bottom, readable way.

Example Without Async/Await (Using Promise)


fetch("https://api.example.com/data")
.then(response => response.json())
.then(data => {
  console.log(data);
})
.catch(error => {
  console.log(error);
});

Example Using Async/Await


async function loadData() {
  try {
    let response = await fetch("https://api.example.com/data");
    let data = await response.json();
    console.log(data);
  } catch(error) {
    console.log(error);
  }
}
loadData();

Note: This example is very easy to read and maintain.

Async/Await vs Promise

Feature Promise (.then) Async/Await
Code Readability Moderate Very High
Syntax .then() chaining Synchronous-like syntax
Error Handling .catch() try…catch
Learning Curve Medium Easy
Modern Usage Common Very Common

Error Handling with Async/Await

You can handle errors through try and catch


async function getUser() {
  try {
    let res = await fetch("https://api.example.com/user");
    let user = await res.json();
    console.log(user);
  } catch(err) {
    console.log("Error:", err);
  }
}

When Should You Use Async/Await?

Async/Await is commonly used when you are working with the following things.

  1. When you call the API.
  2. It is used for Database queries.
  3. It is used for File uploads/downloads.
  4.  It is used for Timers and delays.
  5. It is used for Server requests.

Note: It is widely used in frameworks like Angular, React, and Node.js

Advantages of Async/Await

There are many advantages of Async/Await.

  1. When we use async/await then code will be cleaner and more readable.
  2. It is used to make debugging easier.
  3. It is used for Better error handling.
  4. It is used to avoid callback hell.
  5. It works perfectly with Promises.

Real-Life Example of Async/Await in JavaScript

Fetching User Profile from an API

Suppose you logged into the website, then the system needs to fetch the user’s profile information from a server. Since the data comes from a server, it takes time, so this is an asynchronous operation.

Using async/await, we can write asynchronous code that looks simple and similar to synchronous code.

Example:


function fetchUserProfile() {
    return new Promise(function(resolve) {
        setTimeout(function() {
            resolve({
                name: "John",
                email: "john@abc.com",
                role: "Admin"
            });
        }, 2000);
    });
}

async function displayUserProfile() {
    console.log("Fetching user profile...");

    let user = await fetchUserProfile();

    console.log("Name:", user.name);
    console.log("Email:", user.email);
    console.log("Role:", user.role);
}

displayUserProfile();

Output:

Fetching user profile… Name: John
Email: john@abc.com
Role: Admin

Explanation:

  1. The async keyword is used to declare an asynchronous function.
  2. The await keyword pauses the execution until the Promise is resolved.
  3. fetchUserProfile() returns a Promise that simulates fetching data from a server.
  4. Once the data is received, the program continues execution.

Interview Questions

Q 1: What is async/await in JavaScript?
Ans: async/await is a modern way to handle asynchronous operations in JavaScript. It allows developers to write asynchronous code that looks like synchronous code.
Q 2: What does the async keyword do?
Ans: The async keyword is used to declare a function that always returns a Promise.
Q 3: What does the await keyword do?
Ans: The await keyword pauses the execution of an async function until the Promise is resolved or rejected.
Q 4: Can we use await without async?
Ans: No. The await keyword can only be used inside an async function.
Q 5: Why is async/await better than Promises?
Ans: Async/await makes code:
More readable
Easier to debug
Less nested

JavaScript Async/Await – Objective Questions (MCQs)

Q1. Which keyword is used to declare an async function?






Q2. The await keyword can be used only inside ______.






Q3. What does an async function always return?






Q4. await pauses execution until the Promise is ______.






Q5. Async/Await is built on top of ______.






Conclusion

Async/await is a modern JavaScript feature, and it is used to handle asynchronous programming. It is built on top of Promises and allows developers to write asynchronous code in a clear and readable way.

Async/await is widely used in real-world applications such as API requests, database calls, authentication systems, and file operations.

Write Cleaner Async JavaScript