Learn Programming, Tech & Coding · Free Online Tools

IT Question Answer
Back to JavaScript
Understanding Async/Await in JavaScript

Understanding Async/Await in JavaScript

JavaScript1,634 viewsBy Admin
javascriptunderstandingasyncawait

What is Async/Await?

async/await is syntax (introduced in ES2017) that lets you write asynchronous, Promise-based code as if it were synchronous — no .then() chains, no callback pyramids.

From Promises to Async/Await

// Promise style
function getUser() {
  return fetch("/api/user")
    .then(res => res.json())
    .then(user => console.log(user))
    .catch(err => console.error(err));
}

// async/await style — same thing, cleaner
async function getUser() {
  try {
    const res = await fetch("/api/user");
    const user = await res.json();
    console.log(user);
  } catch (err) {
    console.error(err);
  }
}

Key Rules

  • await can only be used inside an async function (or top-level in ES modules).
  • await pauses the function until the Promise resolves, then returns its value.
  • An async function always returns a Promise.
  • Use try/catch for error handling instead of .catch().

Running Tasks in Parallel

// ❌ Slow — runs one after another (sequential)
const a = await fetchA(); // 1s
const b = await fetchB(); // 1s  → total 2s

// ✅ Fast — runs at the same time
const [a, b] = await Promise.all([fetchA(), fetchB()]); // total 1s

Common Mistake

Forgetting await means you get the Promise object instead of its value:

const data = fetch("/api");        // ❌ data is a Promise
const data = await fetch("/api");  // ✅ data is the Response

FAQs

Is async/await faster than Promises?

No — it compiles to the same Promise machinery. It is purely about readability.

How do I handle errors for multiple awaits?

Wrap them in a single try/catch, or use Promise.allSettled() when you want every result regardless of failures. More in our JavaScript section.