Skip to content

Latest commit

 

History

History
118 lines (90 loc) · 3.37 KB

File metadata and controls

118 lines (90 loc) · 3.37 KB

Async/Await

What is Async/Await?

  • Async/Await is syntactic sugar over Promises.
  • Introduced in ES2017 to make async code look synchronous.
  • async: Marks a function as asynchronous, so it returns a Promise.
  • await: Pauses execution inside an async function until the awaited Promise settles (fulfilled or rejected).

Syntax

async function fetchData() {
  try {
    const data = await fetch('https://api.example.com/data');
    const json = await data.json();
    console.log(json);
  } catch (error) {
    console.error(error);
  } finally {
    console.log('Done');
  }
}

How it works

  • async function always returns a Promise.
  • await:
    • Waits for a Promise to resolve.
    • Extracts its resolved value.
    • If the Promise rejects, await throws the rejection as an error (must handle with try/catch).
  • Execution is paused only inside async functions, but other code continues to run (non-blocking).

Key Rules

  • await can only be used inside an async function (or at top-level in modules, ES2022+).
  • If you await a non-Promise value, it just wraps it with Promise.resolve(value).
  • Errors are caught with try/catch instead of .catch() chaining.
  • You can await multiple Promises in parallel using Promise.all() for efficiency.

Example – Sequential vs Parallel

Sequential

async function sequential() {
  const a = await getData(1);
  const b = await getData(2);
  console.log(a, b); // Runs one after another
}

Parallel

async function parallel() {
  const [a, b] = await Promise.all([getData(1), getData(2)]);
  console.log(a, b); // Runs in parallel
}

Tip: For independent tasks, prefer parallel to save time.

Error Handling

async function fetchWithErrorHandling() {
  try {
    const result = await riskyOperation();
    console.log(result);
  } catch (err) {
    console.error('Error:', err);
  }
}

Common Interview Questions

Basic

  1. What is async/await and why was it introduced?
  2. What does async do to a function's return value?
  3. Can you use await outside of an async function? (Only with top-level await in ES2022+)
  4. How does error handling differ between Promises and async/await?

Intermediate

  1. How do you run multiple async operations in parallel using async/await?
  2. What happens if you await a non-Promise value?
  3. Is async/await blocking? (No, it pauses only the async function, not the whole thread.)

Advanced / Tricky

  1. Explain the relationship between async/await and the microtask queue.

  2. Why is using await inside a loop often a performance issue? How to fix it? (Because it forces sequential execution — fix with Promise.all.)

  3. How to implement a timeout with async/await?

async function fetchWithTimeout(ms) {
  const timeout = new Promise((_, reject) =>
    setTimeout(() => reject('Timeout'), ms)
  );
  return Promise.race([fetch('url'), timeout]);
}

Quick Comparison — Promises vs Async/Await

Feature Promises (.then/.catch) Async/Await
Readability Can get nested Looks synchronous
Error Handling .catch() try/catch
Parallel Execution Promise.all() Promise.all()
Debugging Stack traces less clear Stack traces clearer