async / await

Syntax for writing promise-based code that reads like ordinary sequential code — await pauses only the async function it's inside.

                async function f() { const x = await somePromise; }
              

Purpose

An async function always returns a promise. Inside it, await pauses execution at that line until the awaited promise settles, then resumes with its resolved value (or throws, if it rejected) — all without blocking anything outside that function.

Syntax

async function getGreeting() {
  try {
    const name = await lookUpName();
    return `Hello, ${name}!`;
  } catch (error) {
    console.error('Could not look up name:', error.message);
    return 'Hello, stranger!';
  }
}

getGreeting().then((greeting) => console.log(greeting));

Behavior notes

  • await can only be used directly inside an async function (or, in modern module code, at the top level of a module).
  • A rejected awaited promise throws inside the async function — catch it with an ordinary try/catch, exactly as with a synchronous throw.
  • An async function’s return value is automatically wrapped in a resolved promise, even if the function body doesn’t explicitly return a promise itself.
  • Awaiting several independent promises one at a time (await a(); await b();) runs them sequentially, wasting time if they don’t depend on each other — use Promise.all (see Promise) to run them concurrently instead.

Common mistakes

  • Assuming await blocks the entire program rather than just the function it’s in.
  • Awaiting requests sequentially that could run concurrently with Promise.all.
  • Forgetting await before a promise-returning call, which leaves you with an unresolved Promise object instead of its eventual value.

Runtime notes

Core ECMAScript (ES2017), identical behavior across every current browser and Node version.

Taught in these lessons

Related reference