DEV Community

loading...
Cover image for How to Use async/await with The Fetch API in JavaScript

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

Mehdi Aoussiad
Self-taught Front End Web Developer | Technical Writer
Originally published at webdevidea.com ・4 min read

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});
Enter fullscreen mode Exit fullscreen mode

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));
Enter fullscreen mode Exit fullscreen mode

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
});
Enter fullscreen mode Exit fullscreen mode

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
});
Enter fullscreen mode Exit fullscreen mode

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.

Discussion (4)

Collapse
lukeshiru profile image
LUKESHIRU

As you can see, the syntax now is cleaner.

That depends on your definition of "cleaner". Don't get me wrong, async/await makes async code easier to understand to some folks not used to JavaScript's asynchronicity. When I say it depends, is because from some (myself included), this:

const fetchJSONOrLog = (input, init) =>
    fetch(input, init)
        .then(response => response.json())
        .catch(console.error);
Enter fullscreen mode Exit fullscreen mode

Is way more cleaner and easier to reuse and maintain than this:

async function fetchJSONOrLog(input, init) {
    try {
        const response = await fetch(input, init);
        const data = await response.json();
        return data;
    } catch (error) {
        console.error(error);
    }
}
Enter fullscreen mode Exit fullscreen mode

async/await (like class) were mainly added to JS to make some complicated scenarios easier to express in code. One good example where async/await shines is in async iterators which are a pain. This obviously doesn't mean that we should be using async/await every time, from my PoV ideally we should default to just use Promises, and add syntax sugar only when is needed.

Cheers!

Collapse
aoussiadmehdi profile image
Mehdi Aoussiad Author

Me too, I don't use Async/await all the time. But I prefer to use it.

Collapse
swarnaliroy94 profile image
Swarnali Roy

Informative!

Collapse
aoussiadmehdi profile image
Mehdi Aoussiad Author

Thank you!