Advance JavaScript (DOM, BOM, Web API) / Asynchronous JavaScript

Async and Await

❓ What is async/await?

  • async and await are syntactic sugar over Promises.

  • They make asynchronous code look and behave like synchronous code.

  • Easier to read, easier to debug, avoids callback hell.


🔹 1. async Keyword

  • A function becomes asynchronous when you add async before it.

  • An async function always returns a Promise.

Example:

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

greet().then(res => console.log(res));  // Hello

Even though you return a string, JS wraps it in a Promise.


🔹 2. await Keyword

  • await pauses the execution of the function until the Promise settles.

  • It can only be used inside an async function.

  • It returns the resolved value of the Promise.

Example:

function fetchUser() {
  return new Promise(resolve => {
    setTimeout(() => resolve("User fetched"), 1000);
  });
}

async function getUser() {
  const user = await fetchUser();
  console.log(user);
}

getUser();
User fetched

✏️ Real-Life Example

☕ Think of await like waiting in a queue:

  • You order coffee → (Promise is created)

  • You wait until the coffee is ready → (await)

  • After the coffee is ready, you continue your work.


🔴 Handling Errors in async/await

Use try/catch instead of .catch():


⏰ Multiple Awaits — Promise Chaining with async/await

Looks synchronous but is still asynchronous.


↔️ Parallel Execution with Promise.all()

Avoid doing this (slow):

const a = await task1();
const b = await task2();

Better:

const [a, b] = await Promise.all([task1(), task2()]);

Runs both tasks at the same time.


⭐ Where async/await Shines

  • API calls

  • Database queries

  • Reading/writing files

  • Delayed tasks (setTimeout)

  • Heavy async flows (login → fetch data → render)