🔁 JavaScript Asynchronous Function

📘 What is an async function?

An asynchronous function is a special type of function in JavaScript defined using the async keyword. It allows you to write non-blocking code in a more readable and cleaner way using await.

It always returns a Promise.

🔍 Why use async functions?

🧠 Syntax


async function functionName() {
  // You can use await inside here
}
      

⚙️ Keywords

📦 Example 1: Basic Async Function


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

greet().then(msg => console.log(msg)); // Output: Hello!
      

⏳ Example 2: Using await


function fetchData() {
  return new Promise(resolve => {
    setTimeout(() => resolve("Data loaded"), 2000);
  });
}

async function loadData() {
  console.log("⏳ Loading...");
  const data = await fetchData(); // Waits for 2 seconds
  console.log("✅", data);
}

loadData();
      

🧩 Real Life Analogy

Imagine ordering a pizza 🍕. You place the order (fetchData()), then go do other stuff while you wait. When it arrives, you eat it (await). Async functions let your program do something else while waiting, instead of sitting idle.

📌 Tips

✅ Example with Error Handling


async function getUser() {
  try {
    const response = await fetch("https://jsonplaceholder.typicode.com/users/1");
    const user = await response.json();
    console.log(user);
  } catch (err) {
    console.error("Fetch error:", err);
  }
}

getUser();
      

📝 Summary