← Back to libraryQuestion 137 of 468
🟨JavaScriptIntermediate

async / await

📌 Definition:

async/await is syntactic sugar over Promises that lets you write asynchronous code that reads like synchronous code. An async function always returns a Promise, and await pauses execution until a Promise settles.

📖 Detailed Explanation:

Declaring a function async makes it return a promise automatically — a returned value becomes the resolved value, a thrown error becomes a rejection. Inside an async function, await unwraps a promise: it suspends the function (without blocking the main thread) until the awaited promise settles, then resumes with the resolved value or throws the rejection. This lets you use ordinary try/catch for async error handling. A key performance point: sequential awaits run one after another, so independent operations should be started together (e.g., await Promise.all([...])) rather than awaited in series.

🔑 Key Points:
  • async function always returns a Promise
  • await pauses the function until the promise settles (non-blocking)
  • Use try/catch around await for error handling
  • Independent awaits in series are slow — parallelize with Promise.all
🌍 Real-World Example:

A Playwright test: async function login(page){ await page.fill('#user', 'qa'); await page.fill('#pass', 'pw'); await page.click('#submit'); await expect(page).toHaveURL('/dashboard'); } reads top-to-bottom like sync code, but every step is asynchronous.

🎯 Scenario-Based Interview Question:

This code takes 3 seconds: const a = await getA(); const b = await getB(); const c = await getC(); (each takes 1s and they are independent). How do you make it take ~1 second?