Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 19

Async/Await Under the Hood: Promises and Pausing

Recommended resources

Welcome to the next lesson in our deep dive into JavaScript's asynchronous model. In our previous session, you mastered the intricate dance of the event loop, learning to predict the exact execution order of macrotasks, microtasks, and rendering steps. We established that the microtask queue has a high-priority, run-to-completion policy, a crucial piece of the puzzle.

Today, we'll see how that puzzle piece unlocks the true nature of async/await. You use this syntax daily to write clean, readable asynchronous code, but how does it actually work? This lesson demystifies async/await by revealing it for what it is: elegant syntactic sugar over the very Promise and microtask mechanics you just learned. We'll peel back the abstraction to understand what "pausing" a function truly means in a single-threaded environment, giving you the deep internal knowledge expected of a senior engineer.

async/await: A More Readable Promise Chain

At its core, async/await is a language feature designed to make promise-based code look and behave more like synchronous code, without sacrificing the non-blocking nature of JavaScript.

Let's start with a quick refresher. This short video from Fireship effectively illustrates how async/await cleans up promise chains.

The Async Await Episode I Promised

This video provides a concise overview of async/await as syntactic sugar and explains the basic roles of the async and await keywords.

Watch the segment from the introduction. It will quickly demonstrate the syntax and highlight how async functions always return a promise, while await pauses the function to get the resolved value.

As the video shows, async/await is built on two keywords that work together:

  1. async: When you place async before a function declaration, it ensures two things:

    • The function will always return a promise.
    • If you return a non-promise value (e.g., return 42), the engine implicitly wraps it in a resolved promise for you (Promise.resolve(42)).
    • It enables the use of the await keyword inside that function.
  2. await: This keyword can only be used inside an async function. When placed before a Promise, it does something that seems like magic: it "pauses" the execution of the async function until that Promise settles (either resolves or rejects). Once the Promise resolves, await unwraps the value, so you can assign it directly to a variable.

But what does "pausing" mean? How can a single-threaded language pause a function without blocking everything else? The answer lies in a feature that predates async/await: Generators.


The Engine of async/await: Generators and Coroutines

Long before async/await, developers used a pattern called generator-based coroutines to achieve synchronous-looking async code. In fact, async/await is a direct implementation of this pattern. Understanding generators is the key to understanding how await works.

A generator function, declared with function*, is a special kind of function that can be paused and resumed. The yield keyword is used to specify the pause points.

function* myGenerator() {
  console.log("Starting...");
  const value1 = yield 1; // Pause 1
  console.log("Resumed with:", value1);
  const value2 = yield 2; // Pause 2
  console.log("Resumed with:", value2);
  return "Finished!";
}

const gen = myGenerator(); // Calling it doesn't run the code, it creates an iterator.

console.log(gen.next());        // Runs until the first yield. Logs "Starting...". Returns { value: 1, done: false }
console.log(gen.next("Hello")); // Resumes, passing "Hello" as the result of the first yield. Logs "Resumed with: Hello". Returns { value: 2, done: false }
console.log(gen.next("World")); // Resumes, passing "World". Logs "Resumed with: World". Returns { value: "Finished!", done: true }

Notice the "ping-pong" interaction. We call next() to run a piece of the function, and yield sends a value back out. We can also pass a value into next() to send data back to the paused yield expression.

Now, what if we yield a Promise and use its resolution to call next()? This is the core idea of a coroutine runner.

The following article provides a superb explanation of how to build a simple runner that automates this "ping-pong" between yielded promises and the generator's next() call.

Understanding Generator-Based Coroutines in JavaScript | Hassam on Code

This article from Hassam Ali is one of the clearest explanations of the evolutionary path from generators to async/await. It will walk you through building the very mechanism that async/await uses under the hood.

First, read the section on generators to solidify your understanding of function*, yield, and next(). Next, study the coroutine runner implementation. This is the most critical part. See how the handle function uses Promise.resolve() and .then() to recursively call generator.next() with the resolved value. Finally, look at the section comparing the generator pattern to the final async/await syntax. Then, examine the Babel transformation example. This shows you exactly how your async function is "desugared" into a generator and a runner function (_asyncToGenerator).

The _asyncToGenerator function you saw in the article is the proof. When you write an async function, the JavaScript engine (or a transpiler like Babel) effectively transforms it into:

  1. A generator function where each await becomes a yield.
  2. A runner function (the "coroutine") that executes the generator, handling the promises that are yielded.

So, when your async function "pauses" at an await, what's happening mechanically is:

  1. The await expression (e.g., fetch(...)) is executed, and it returns a Promise.
  2. The async function's execution is suspended, and the Promise is yielded out to the engine's internal "runner".
  3. Crucially, control is returned to the event loop. The call stack unwinds. Your browser is not blocked; it can handle user input, run other tasks, etc.
  4. The engine's runner attaches a .then() callback to the yielded Promise.
  5. When the Promise eventually resolves, its .then() callback is placed in the microtask queue.
  6. As we know from the last lesson, the event loop will execute this microtask as soon as the call stack is clear.
  7. The microtask's job is to resume the suspended generator, passing the resolved value back in as the result of the yield expression. Execution continues until the next await or the end of the function.

Mental Model: async Functions as State Machines

A powerful way to think about an async function is not as a single block of code, but as a generator-based state machine. Each await is a transition point where the function's state (its local variables, which line it's on) is saved, and execution is suspended. The rest of the function, the part after the await, is called the continuation.

The engine essentially packages this continuation into a microtask and says, "Run this later, when the promise resolves."

This diagram from V8's engineers illustrates the internal objects created to manage this process.

When an `async` function (`bar`) hits an `await`, it creates a `JSPromise` and suspends its own execution state inside a `JSGeneratorObject`. The code after the `await` is packaged into `fulfill_handler` and `reject_handler` functions (the "continuation") and attached to the promise as a "Promise Reaction." When the promise resolves, this handler is run as a microtask, which resumes the generator.

The concept of chaining these continuations is visualized well in the next diagram. Each async function call prepares a "continuation" (a resume plan) for what to do after its await resolves.

Nested `async` functions create a chain of continuations. `foo` is paused waiting for `bar`. `bar` is paused waiting for `baz`. When `baz`'s promise resolves, its continuation runs, which in turn resolves `bar`'s promise, and so on up the chain.

The Cost of Convenience

This mechanism is incredibly powerful, but it's not free. As the dev.to article below explains, every async function introduces some overhead compared to a raw promise chain.

Best Practices for ES2017 Asynchronous Functions (`async`/`await`) - DEV Community

This article dives into the practical performance implications and best practices that stem from understanding async/await's inner workings.

Read the introduction and the section on "pausable functions", which discusses the initial overhead. Focus on the section Refrain from using return await. It explains a common anti-pattern and why it's inefficient. Skim the footnotes, especially the first one, which describes how V8 optimized this process by reducing the number of promises created. This gives you historical context on why async/await was once much slower.

The key insight is that return await is often redundant. The await pauses the function, waits for the promise to resolve, unwraps the value, and then the return immediately re-wraps it in a promise (because it's an async function). This adds an unnecessary tick to the microtask queue and keeps the function's frame on the call stack longer than needed. Simply return somePromise() passes the promise up the chain directly.

The one time return await is useful is when it's inside a try...catch block, as it allows the catch block to handle a rejection from the awaited promise before the function returns. Without the await, the promise would be returned immediately, and any rejection would have to be handled by the caller.


Conclusion

You've now seen behind the curtain of async/await. It's not magic; it's a brilliant piece of syntactic sugar built upon the foundation of Promises and Generators, orchestrated by the event loop's microtask queue.

Key Takeaways:

  • async/await is syntactic sugar for generator-based coroutines.
  • An async function is transformed into a generator function and a "runner" that executes it.
  • The await keyword yields a Promise, suspending the function and returning control to the event loop. The function's state is preserved.
  • The "runner" uses Promise.then() to schedule a microtask that resumes the generator with the resolved value.
  • This "pausing" is non-blocking; the event loop is free to process other tasks.
  • This mechanism has a small performance overhead compared to raw promises, and patterns like return await can be unnecessarily inefficient.

In our next lesson, we will pivot to error handling in this asynchronous world. We'll examine how errors propagate through Promise chains and how async/await with try/catch provides a more robust and familiar way to manage exceptions in your asynchronous code.