Skip to content
jshacks.dev
Async

How await Works Under the Hood

See what await does step by step, how the function pauses and resumes through microtasks, and why await always yields even for an already settled value.

6 min read
Summarize in AI
Flat illustration of jobs on a conveyor heading to a rack of workers, with the JavaScript, Redis, Node.js and Apache Kafka logos.

await looks like a pause button, and it behaves like one from inside the function, but nothing pauses the thread. The function is suspended, its state is saved and control returns to whoever called it. When the awaited promise settles, a microtask resumes the function exactly where it stopped. Understanding those steps explains questions that otherwise look arbitrary: why await 5 still yields, why two awaits in a row take two turns of the microtask queue, why an await inside try catches errors and why logs from concurrent functions interleave in a specific order. This post walks through the mechanism on Node.js 24 with printed output, and shows the same function rewritten with then to make the transformation visible.

What await does, in four steps

When a function evaluates await expression, four things happen.

  1. The expression is evaluated, and the result is converted to a promise with Promise.resolve, so plain values and thenables are accepted.

  2. The function's execution context is suspended, saving local variables and the position in the code.

  3. Control returns to the caller, or to the event loop if the function was already resumed from a microtask.

  4. When the promise settles, a microtask is queued to resume the function, with the value as the result of the await or the reason thrown at that point.

Step 4 is why await never resumes synchronously, even if the promise is already settled.

JavaScript
async function demo() {
  console.log("A: before await");
  await Promise.resolve();
  console.log("C: after await");
}

demo();
console.log("B: after calling demo");
Text
A: before await
B: after calling demo
C: after await

The promise was already fulfilled, and the code after await still ran after the caller's next line. Resuming always goes through the microtask queue, which gives the caller a chance to finish its own synchronous work first.

Await on a plain value

Because step 1 wraps the value, await 5 is the same as await Promise.resolve(5). It yields, and then resumes with 5.

JavaScript
async function plain() {
  const value = await 5;
  console.log("resumed with", value);
}

plain();
console.log("caller continues");
Text
caller continues
resumed with 5

People are sometimes surprised that awaiting a non-promise is allowed and still delays the continuation. It is a deliberate rule that keeps the timing the same whether a function returns a value or a promise, so callers do not depend on which one they got.

The same function written with then

An async function is roughly a state machine that the engine builds for you. The code before an await runs now, and the code after becomes a callback attached to the awaited promise. Here is a function with two awaits and its manual equivalent.

JavaScript
const delay = (ms, value) =>
  new Promise((resolve) => setTimeout(() => resolve(value), ms));

async function withAwait() {
  const a = await delay(10, "a");
  const b = await delay(10, "b");
  return a + b;
}

function withThen() {
  return delay(10, "a").then((a) =>
    delay(10, "b").then((b) => a + b),
  );
}

console.log(await withAwait());
console.log(await withThen());
Text
ab
ab

The second then is nested so it can still see a, which shows why await is more convenient: it keeps earlier variables in scope without nesting. The engine does something equivalent by saving the locals across the suspension.

Error handling: throw at the resume point

When the awaited promise rejects, the function resumes by throwing the reason at the await expression. That is why an ordinary try/catch works.

JavaScript
async function risky() {
  try {
    await Promise.reject(new Error("remote failed"));
    console.log("not printed");
  } catch (error) {
    console.log("caught at the await:", error.message);
  } finally {
    console.log("finally runs");
  }
}

await risky();
Text
caught at the await: remote failed
finally runs

Without the try, the throw would escape the function body, and the function's own promise would reject. That is how errors travel up a chain of awaiting functions, one rejection after another.

Ordering between concurrent functions

When two async functions run in the same turn, their continuations are queued as microtasks in the order the awaited promises settled, and each await costs one trip through the queue. That gives a predictable interleaving.

JavaScript
async function first() {
  console.log("first: 1");
  await null;
  console.log("first: 2");
  await null;
  console.log("first: 3");
}

async function second() {
  console.log("second: 1");
  await null;
  console.log("second: 2");
  await null;
  console.log("second: 3");
}

first();
second();
console.log("main done");
Text
first: 1
second: 1
main done
first: 2
second: 2
first: 3
second: 3

Each function ran up to its first await, the main script finished and then the two functions took turns, one step per microtask round. This round-robin is a reading of the queue and not a feature to rely on in production code, but it explains why logs from concurrent tasks alternate.

Why awaiting a native promise is cheap

In older engines, await promise took three microtask ticks, because the promise was wrapped again and a then was attached to the wrapper. A change to the specification in 2018 made awaiting a native promise take one tick, by using the promise directly when its constructor matches. The practical result is that await on a native promise has a small, fixed cost, and awaiting something that is only a thenable still costs more, since it is converted through a new promise and a call to its then. This is one reason to prefer native promises over custom thenables on hot paths.

What await cannot do

await pauses only the function it appears in. It does not block the thread, and it does not make slow code fast. Code after the call to an async function runs as soon as the function reaches its first await, and a long computation inside the function still holds the thread until it returns.

JavaScript
async function compute() {
  let total = 0;
  for (let i = 0; i < 1e7; i++) total += i;
  await null;
  return total;
}

setTimeout(() => console.log("timer fired"), 0);

const promise = compute();
console.log("compute returned a promise");
console.log(await promise);
Text
compute returned a promise
49999995000000
timer fired

The loop ran inside the call to compute(), before the first await, so the timer could not fire until after the whole thing. The await null inside gave nothing to the timer either, because microtasks run ahead of timers.

Where await is not allowed

Inside a regular function, await is a syntax error, and the fix is to mark the function async. At the top level of an ES module, await works without a function, and the module itself waits. In CommonJS files there is no top-level await, so wrap the code in an async function and call it.

Debugging implications

Since a suspended function is not on the call stack, a stack trace printed after an await does not include the callers that were waiting. Engines patch this with async stack traces, which reconstruct the chain of awaiting functions, and V8 does so for async functions that use await directly. The chain is lost when a promise is handed through then callbacks or combinators in between, which is one practical reason to keep await straight and use fewer layers.

What this means for how you write code

Knowing that every await costs a trip through the microtask queue changes a few habits. Do not await inside a hot loop when the values are already available, since each await adds a suspension and a resumption. Gather independent promises and await them together. And do not rely on the exact number of ticks between two awaits, because that detail has changed between engine versions and may change again. Code that depends on one function finishing "just before" another, by counting microtasks, is correct only by accident. Express ordering with promises you can await, and the compiler of intent is clear to the next reader as well.

Share

Keep reading

Flat illustration of an editor window full of code, with the Google Chrome, JavaScript and npm logos.
Browser

script Tags: async, defer and type=module

Compare classic, async, defer and module script tags: when each downloads, when each runs, how order is kept and which one to pick for each kind of script.

6 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.