How to Use async/await with The Fetch API in JavaScript

Using the fetch API is a good idea if you want to make HTTP requests and get data from APIs. It's easy to use, you only need to know JavaScript.

The fetch API is an alternative to the old XML HttpRequest. However, the majority of developers prefer to use fetch because it's very simple and straightforward. Since the method fetch() returns a promise, we can use async/await syntax to make our code cleaner and easy to read.

In this article, we'll learn about the fetch API and how to use it with async/await syntax. Let's get started.

Introduction to the fetch API

The fetch API is the easiest way to assess resources in the network. It's a tool that allows us to make HTTP requests using different methods such as GET, POST, etc.

To start making requests, we use the method fetch() and pass it the required arguments. The fetch method accepts two arguments:

  • The 1st argument: the URL where you want to make the request(in a string). It can also take a response object.
  • The 2nd argument: A configuration object that takes properties for the request method, headers, body, and all other options.
const response = await fetch(URL, {options object});

Since the method fetch() returns a promise, we can use then and catch methods of promises to handle the requests. The promise gets resolved if the request is completed. On the other hand, if the request fails due to any error, the promise will be rejected.

Fetch example without async/await

To make it simple for you, we will provide an example of using fetch to get data from an API. In this example, we will use fetch without async/await just to show you how the syntax looks.

By using fetch, we will try to get a list of users from the JsonPlaceholder fake API.
Here is the example:

fetch('https://jsonplaceholder.typicode.com/users')
.then(res => res.json())
.then(data => console.log(data))
.catch(err => console.log(err));

By default, when you only pass the first argument(API URL) to the method fetch() you're only allowed to do GET requests. That's enough if you only want to get data from an API. However, you can still pass the configuration object as a second argument if you want to do other HTTP requests like POST for example.

In the example above, we used the method fetch and pass it the API URL as a first argument. Since fetch returns a promise, we used then method to get the response from the API in a JSON format and catch method to handle an error if it occurs. As a result, the requested data gets printed in the console. You can take that data and display anywhere on your page if you want.

Using async/await with fetch

As we know, async/await allows us to write asynchronous code in a much cleaner way. It allows us to avoid the headaches of using callbacks and then catch syntax in our code.

That's why I always prefer using async/await when using the fetch API. In this section, we will implement the same example that we did above, but now using async/await syntax.

To use async/await, make sure to create an asynchronous function by using the keyword async. The keyword await is permitted inside the function.
Here is the example:

const API_URL = 'https://jsonplaceholder.typicode.com/users';

async function fetchUsers() {
  const response = await fetch(API_URL)
  const users = await response.json();
  return users;
}

fetchUsers().then(users => {
  users; // fetched users
});

As you can see, the syntax now is cleaner. We only added the keyword async to the begining of the function. Then we used the keyword await when assigning the variables. Since fetchUsers is an asynchronous function, it returns a promise. As a result, we used one then method to handle the promise.

So this is how to get data from an API using fetch and async/await. Now you can do anything with the data users that we got from the API. You can display it on the page if you want.

You can also use try and catch to handle errors if you want. Here is the same example above, but now adding error handling:

const API_URL = 'https://jsonplaceholder.typicode.com/users';

async function fetchUsers() {
 try{
   const response = await fetch(API_URL)
   const users = await response.json();
   return users;
  }catch(err){
    console.error(err); 
  }
}

fetchUsers().then(users => {
  users; // fetched users
});

If you're not familiar with error handling in JavaScript, I suggest that you learn about it from other resources. It's a useful thing to know.

Conclusion

The fetch API is very useful when it comes to working with APIs in general. Combining fetch with async/await is a good way to make your code cleaner and easy to read.

Thank you for reading. If you're interested in more webdev content, make sure to visit our new blog WebDevIdea.

26