learn2kode.in

Introduction to Async / Await in JavaScript

Async / Await is a modern JavaScript feature that makes working with asynchronous code simpler, cleaner, and more readable. It is built on top of Promises and helps you write asynchronous logic that looks and behaves like synchronous code.

Before async/await, developers relied heavily on callbacks and Promise chains, which could become hard to read and maintain. Async/await solves this problem.

Why Use Async / Await?

What Is async?

The async keyword is used to declare a function that always returns a Promise.

Example

async function greet() {
  return "Hello World";
}

greet().then(message => console.log(message));
Even though we return a string, JavaScript automatically wraps it inside a Promise.

What Is await?

The await keyword is used inside an async function to pause execution until a Promise is resolved.

async function fetchData() {
  let response = await fetch("https://api.example.com/data");
  let data = await response.json();
  console.log(data);
}
Async / Await with Promises
Without Async / Await
fetch(url)
  .then(res => res.json())
  .then(data => console.log(data))
  .catch(error => console.log(error));
With Async / Await
async function getData() {
  try {
    const res = await fetch(url);
    const data = await res.json();
    console.log(data);
  } catch (error) {
    console.log(error);
  }
}
Error Handling with Try…Catch
Async/await uses try…catch blocks to handle errors.
async function loadUser() {
  try {
    const response = await fetch("/user");
    const user = await response.json();
    console.log(user);
  } catch (error) {
    console.error("Error loading user:", error);
  }
}

Async / Await vs Promises

Feature Promises Async / Await
Syntax .then() chaining Looks synchronous
Readability Medium High
Error Handling .catch() try...catch
Modern Usage Supported Preferred

Common Use Cases of Async / Await

Important Rules to Remember

Best Practices