Skip to main content

Welcome to a Grasp lesson

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

Lesson 67

Simplifying Asynchronous JavaScript with Async/Await

This lesson is built with resources from youtube.com, javascript.info and 1 more site.

Hello! In our last lesson, we mastered the art of chaining Promises with .then() to create clean, sequential asynchronous workflows. We successfully flattened the "Pyramid of Doom" and saw how to pass data from one step to the next.

While Promise chains are a huge improvement over nested callbacks, you might have noticed they still involve writing functions inside of .then() calls. Today, we'll take the final step toward writing truly elegant asynchronous code. We will learn how to use async/await, a modern JavaScript feature that lets you write asynchronous code that looks and reads just like synchronous code.

This lesson directly addresses your goal of mastering modern ES6+ syntax that is fundamental to working with Next.js and TypeScript. async/await is the standard for handling asynchronous operations like data fetching in modern applications.

What is Async/Await?

async/await isn't a new way for JavaScript to handle asynchronous tasks. Instead, it's what we call syntactic sugar built on top of the Promises you already understand. It's a different, more intuitive way to write and read code that uses Promises.

The core idea is simple: what if you could just "pause" your function and wait for a Promise to finish, without using a .then() callback?

The following video provides an excellent introduction to why async/await was created and the problem it solves.

Async Await vs. Promises - JavaScript Tutorial for beginners

Watch this introductory segment from the 'Async Await vs. Promises' video by ColorCode. It perfectly sets the stage by comparing a .then() block to the ideal, synchronous-looking code we want to write.

Watch from the beginning to 02:38. Pay attention to the annoyance the instructor expresses with having the result variable 'trapped' inside a .then() block, and how await seems to magically solve this.

This "magic" is enabled by two new keywords: async and await. They work together.


The async and await Keywords

Let's break down these two keywords. They are simple but have very specific rules.

Async/await

The article 'Async/await' from the well-respected javascript.info site provides a clear and concise definition of these two keywords. Let's read their explanation.

Read the first two sections, 'Async functions' and 'Await'. Focus on the two key effects of the async keyword and the single, powerful purpose of the await keyword.

Let's summarize the key rules from that reading:

  1. The async Keyword:

    • You place it before a function declaration (async function myFunction() { ... }).
    • It does two crucial things:
      • It ensures the function always returns a Promise. If you explicitly return a value like return 42;, async will wrap it in a resolved Promise for you (Promise.resolve(42)).
      • It allows you to use the await keyword inside that function.
  2. The await Keyword:

    • It can only be used inside an async function. Trying to use it elsewhere will cause a syntax error.
    • You place it in front of a Promise (e.g., let value = await myPromise;).
    • It pauses the execution of the async function until the Promise settles (either resolves or rejects).
    • Once the Promise resolves, await gives you the resolved value directly.

From Promise Chains to async/await

Now for the best part: refactoring a .then() chain into the much cleaner async/await syntax. Let's take the common task of fetching data from an API.

With a Promise chain, it looks like this:

// Using .then() chain
function fetchUser() {
  fetch('https://api.github.com/users/lydiahallie')
    .then(response => {
      // response.json() also returns a Promise!
      return response.json();
    })
    .then(data => {
      console.log('Data fetched with .then() chain:');
      console.log(data);
    })
    .catch(error => {
      console.error('Error:', error);
    });
}
fetchUser();

Now, let's convert this to use async/await. Notice how the nested .then() is gone and the code reads like a series of simple, synchronous steps.

// Using async/await
async function fetchUserAsync() {
  // We'll talk about the try...catch block shortly
  try {
    const response = await fetch('https://api.github.com/users/lydiahallie');
    const data = await response.json(); // We 'await' the second promise too
    
    console.log('Data fetched with async/await:');
    console.log(data);
  } catch (error) {
    console.error('Error:', error);
  }
}
fetchUserAsync();

This next video demonstrates this exact refactoring process, solidifying the comparison.

Async Await vs. Promises - JavaScript Tutorial for beginners

Let's return to the ColorCode video. This segment provides a live-coding demonstration of converting a fetch call from using .then() chains to async/await.

Watch from 07:08 to 10:53. The instructor refactors a fetch call that requires two steps (fetch and .json()). Observe the side-by-side comparison of the two syntaxes at the end of the segment.


Under the Hood: How await Pauses a Function

You have a preference for understanding the deep theory, so let's explore what "pausing" a function really means. When the JavaScript engine encounters an await keyword, it doesn't freeze the entire browser. It's much more elegant than that.

The async function's execution is suspended, and its state is put aside. The JavaScript engine is now free to continue running other code, including event handlers, other scripts, or rendering updates. When the awaited Promise finally settles, the engine schedules the async function to resume its execution right where it left off.

This process involves the call stack, event loop, and the microtask queue we've discussed before.

The following animated GIF provides the perfect visualization for this process.

JavaScript Async/Await Execution Flow Visualization
This animation shows how `async/await` works with the JavaScript engine's internal components. When the `async` function `myFunc` is called, it runs until it hits `await`. At this point, the function's execution is paused and it's removed from the call stack. The engine continues with other synchronous code (`console.log('After function!')`). Once the awaited promise resolves, the Event Loop moves the paused function from the Microtask Queue back to the Call Stack to resume execution.

To dig even deeper into this visual, let's turn to the article it comes from.

⭐️🎀 JavaScript Visualized: Promises & Async/Await

The article 'JavaScript Visualized: Promises & Async/Await' by Lydia Hallie, which you've seen before, provides a fantastic textual and visual breakdown of this process.

Read the section titled 'Async/Await'. The text walks you through the steps shown in the animation, explaining how the engine suspends the function, leaves to execute other code, and then returns once the promise is resolved.

Test your understanding!

Based on your understanding of how await pauses a function, what will be the order of the console logs from the following code?

async function myProcess() {
  console.log('A: Process Start');
  
  const value = await new Promise(resolve => {
    setTimeout(() => resolve('C: Promise Resolved'), 1000);
  });

  console.log(value);
  console.log('D: Process End');
}

console.log('B: Before calling process');
myProcess();
console.log('E: After calling process');
Show answer

The console will log the messages in this order:

  1. B: Before calling process
  2. A: Process Start
  3. E: After calling process
  4. C: Promise Resolved
  5. D: Process End

Explanation:

  1. The first log is B, as it's a simple synchronous call.
  2. myProcess() is called. It logs A.
  3. The engine hits await. It pauses myProcess() and goes back to the code that called it.
  4. The next synchronous line, E, is executed immediately. The setTimeout is still running in the background.
  5. After 1 second, the Promise resolves. The event loop brings myProcess() back to the call stack to resume execution.
  6. The resolved value C is logged, followed by the final log D.

Handling Errors with try...catch

So what happens if an awaited Promise rejects? With .then() chains, the error would be caught by a .catch() block. With async/await, a rejected Promise throws an error, just as if you had written throw new Error().

The standard way to handle this is with a tool you might have seen in other programming languages: the try...catch block.

  • You wrap the code that might fail (your await calls) in a try { ... } block.
  • You add a catch (error) { ... } block immediately after to handle any errors that are thrown.

This makes error handling look synchronous and is considered a best practice when using async/await.

Async/await

Let's revisit javascript.info for a clear explanation of error handling in async functions.

Read the section 'Error handling'. It shows how a rejected promise throws an error and how you can catch it using a standard try...catch block. Notice the similarity to handling regular synchronous errors.


Conclusion

You've now learned the modern, preferred way to handle asynchronous operations in JavaScript. By using async/await, you can write code that is significantly more readable and maintainable, especially as your application logic grows more complex.

Key Takeaways:

  • async/await is syntactic sugar over Promises. It doesn't replace them; it provides a better syntax for using them.
  • An async function always returns a Promise and is the only place you can use await.
  • The await keyword pauses the execution of an async function until a Promise settles, then returns its resolved value.
  • This syntax allows you to write asynchronous code that reads top-to-bottom, like synchronous code.
  • Errors from rejected Promises are handled using standard try...catch blocks.

Next Up

We've briefly touched on try...catch, but there's more to robust error handling in asynchronous functions. In our next lesson, we will do a deep dive into handling errors in async/await functions, exploring different patterns and best practices to make your asynchronous code truly production-ready.