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

The power of async-await and the fetch API in JavaScript.

Mehdi Aoussiad
4 min readMar 4, 2022

--

async-await and the fetch API in JavaScript
Photo by Jexo on Unsplash

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 an 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));

--

--

Mehdi Aoussiad

Front-End Web Developer from Morocco. I focus on writing useful articles for you(Web dev/SEO). Follow me on Twitter:➡️ https://twitter.com/AoussiadMehdi

Recommended from Medium

Lists

See more recommendations