layout: bpost title: "How to use Async/Await with Fetch" image: "images/content/updating-angular-cli-projects.png" excerpt: "" categories: [javascript] permalink: /async-await-fetch/

tags: [javascript]

Fetch is the de facto standard for making network requests in web apps. Although fetch() is intuitive to use in most situations, you should be aware of a few subtleties.

This article details the most common applications of the async/await syntax in conjunction with the fetch() function. You'll have the knowledge to perform a data fetch, deal with a fetch error, and abort a data fetch, among other things.

The Fetch API is used to retrieve data from remote servers (using GET, POST, and other methods). Also, files can be downloaded and uploaded via HTTP requests.

Simply invoking the helper function fetch() will initiate a request:

const response = await fetch(resource[, options]);

The fetch() method initiates an HTTP request and returns a promise. The promise is resolved with the Response object when the request is completed. The promise is rejected if the request fails due to network issues.

Since it facilitates work with promises, the async/await syntax works well with fetch().

Let's make a request to get some posts, for example:

const res = await fetch("https://jsonplaceholder.typicode.com/posts");
// ...
console.log(res);

When the request is finished, res is assigned with the request's response object. Let's look at how to extract useful data from the response, such as JSON or plain text, in the following section.

The await fetch() response object is a generic space filler for various data formats.

For example, you can get the JSON object from a fetch response by doing the following:

const res = await fetch("https://jsonplaceholder.typicode.com/posts");
const data = await res.json(); 
console.log(data);

The res.json() method is a Response object method that allows you to retrieve a JSON object from the response. Because the method returns a promise, you must wait for it: await res.json().

The Response object has a plethora of useful methods (all of which return promises):

response.