Learn The Web

Async/Await

Simplifying Asynchronous JavaScript

You've learned how to fetch data from servers using the fetch() API and promises. But working with promises can sometimes be a bit awkward, especially when you have multiple asynchronous operations that depend on each other. That's where async/await comes in. Async/await is a syntactic sugar built on top of promises that makes asynchronous code easier to write and read.

What is Async/Await?

async and await are keywords that were introduced in ECMAScript 2017 (ES8) to simplify asynchronous JavaScript code.

  • async: The async keyword is used to define an asynchronous function. An async function always returns a promise, either implicitly or explicitly.
  • await: The await keyword is used inside an async function to pause the execution of the function until a promise is resolved (fulfilled) or rejected. The await keyword can only be used inside an async function.

Think of async/await as a way to write asynchronous code that looks and behaves more like synchronous code, making it easier to reason about and debug.

Using Async/Await

Here's an example of how to use async/await to fetch data from a server:

async function getUserData(userId) {
  try {
    const response = await fetch(
      `https://jsonplaceholder.typicode.com/users/${userId}`
    );
    const data = await response.json();
    return data;
  } catch (error) {
    console.error("Error fetching user data:", error);
    throw error; // Re-throw the error to be handled by the caller
  }
}
 
// Calling the async function
getUserData(1)
  .then((user) => {
    console.log("User data:", user);
  })
  .catch((error) => {
    console.error("Error:", error);
  });

Let's break down this code:

  1. async function getUserData(userId): Defines an asynchronous function called getUserData that takes a userId as an argument.
  2. try...catch: Handles potential errors during the asynchronous operations.
  3. const response = await fetch(...): Calls the fetch() function to make an HTTP request. The await keyword pauses the execution of the getUserData function until the fetch() promise is resolved (the response is received).
  4. const data = await response.json(): Parses the response body as JSON. The await keyword pauses the execution of the getUserData function until the response.json() promise is resolved (the JSON data is parsed).
  5. return data: Returns the parsed JSON data.
  6. Error Handling: If any error happens inside the try block, the catch block will be triggered.

Benefits

  • Improved Readability: Async/await makes asynchronous code easier to read and understand, especially when dealing with multiple asynchronous operations.
  • Simplified Error Handling: The try...catch statement provides a more straightforward way to handle errors in asynchronous code.
  • Easier Debugging: Async/await makes it easier to debug asynchronous code, as you can step through the code line by line in a debugger, just like synchronous code.

Promises

Async/await is built on top of promises and doesn't replace them. It simply provides a more convenient syntax for working with promises. Underneath the hood, async/await is still using promises.

You can use async/await in combination with promises, or you can use async/await exclusively. It's a matter of personal preference and coding style.

Example: Chaining Multiple Async Operations

Here's an example of how to use async/await to chain multiple asynchronous operations:

async function getPostsByUser(userId) {
  try {
    // Get user data using the previously defined function
    const user = await getUserData(userId);
    console.log("User:", user.name);
 
    // Fetch posts for the user
    const postsResponse = await fetch(
      `https://jsonplaceholder.typicode.com/posts?userId=${userId}`
    );
    // Parse the response as JSON
    const posts = await postsResponse.json();
    console.log("Posts:", posts);
 
    return posts;
  } catch (error) {
    console.error("Error:", error);
  }
}
 
getPostsByUser(1);

This code first calls the getUserData() function (defined previously) to get the user data. Then, it uses the user ID to fetch the user's posts from the JSONPlaceholder API. The await keywords ensure that each asynchronous operation is completed before the next one is started.

Practice and Explore

Async/await is a powerful tool for simplifying asynchronous JavaScript code. Practice using async/await in different scenarios. Experiment with chaining multiple asynchronous operations and handling errors. The more you use async/await, the better you'll understand how to write clean and maintainable asynchronous code.

Last updated on

On this page