learn deep. ship safe.Practice testsFollow ByteMunSubscribe

Concept

Async/await

Writing asynchronous code that reads top to bottom, built on promises.

Async/await explained

async/await is syntax for working with promises that reads like ordinary top-to-bottom code. An async function always returns a promise. Inside it, await pauses only that function until the awaited promise settles, then resumes with its value, or throws its error so you can use a normal try/catch. The rest of the program keeps running in the meantime.

How async/await works

async function loadDashboard(userId) {
  try {
    const user = await getUser(userId);
    // These two don't depend on each other: start both, then wait once.
    const [orders, messages] = await Promise.all([
      getOrders(user.id),
      getMessages(user.id),
    ]);
    return { user, orders, messages };
  } catch (err) {
    reportError(err);
    throw err;
  }
}

Each await hands control back to the event loop; the code after it runs later as a microtask. That is why awaiting things one after another is slower than starting them together when they are independent.

Common mistakes

  • Accidental sequential work. await a(); await b(); takes the sum of both times. If they are independent, use Promise.all([a(), b()]).
  • await inside forEach. forEach ignores the returned promises, so the loop finishes before the work does. Use for...of for one-at-a-time, or Promise.all(items.map(...)) for parallel.
  • Forgetting await. You get a pending promise instead of the value, and errors escape your try/catch.
  • Swallowing errors with an empty catch. Log or rethrow so callers know it failed.

async/await compared with promises and callbacks

Callbacks nest and spread error handling across every level. Promise chains flatten that and centralise errors in .catch. async/await is the same promises underneath, written so the happy path, loops and error handling look like synchronous code.

What interviewers ask about async/await

  • "What does an async function return?" Always a promise, even if you return a plain value.
  • "Does await block the thread?" No, only the current async function; the event loop keeps running other work.
  • "Rewrite this promise chain with async/await", then the reverse.
  • "Run 100 requests, at most 5 at a time." Keep a pool of in-flight promises and start a new one each time one finishes.
Concept map
Async/await

What should you learn before Async/await?

  1. FunctionsReusable blocks of code; in JavaScript they are values that can be passed around and returned.
  2. CallbacksFunctions passed to other functions to be called later, the original way to handle async work.
  3. Promisesasync/await is syntax on top of promises.
  4. The event loopKnowing the microtask queue explains when await resumes.

Connections to other concepts

Practise Async/await

All topics