How to use the Fetch API with async/await (2024)

Fetch API is an asynchronous web API that comes with native JavaScript, and it returns the data in the form of promises.

You use several Web APIs without knowing that they are APIs. One of them is the Fetch API, and it is used for making API requests. Let’s take a look at it.

Fetch API

To put it simply, the Fetch API lets you talk with other APIs. It is a Web API that uses promises to make network requests over the HTTP/1.1 protocol. You can make both same or cross-origin requests using the Fetch API.

Fetch API is included in all modern browsers, and you do not need to import any third-party library through yarn or npm. You can use the fetch API using the fetch method. It takes multiple arguments, including the API endpoint's URL, i.e., the path of the resource you are interested in fetching.

Without async/await

Fetch API uses two objects, Request and Response. This Response object holds the data sent by the API. Fetch sends the Request and returns a promise, which is resolved to the Response object when the request completes. If the request fails, the promise is rejected.

To get the data received in the response, you need to wait for this promise to resolve into the Response object. One way is to use then to capture the response.

js

fetch(

'https://carbonfootprint1.p.rapidapi.com/CarbonFootprintFromCarTravel?distance=100&vehicle=SmallDieselCar',

{

method: 'GET',

headers: {

'x-rapidapi-key': 'your_api_key'

}

}

).then(response => {

console.log(response);

});

Using async/await

A better and cleaner way of handling the promise is through the async/await keywords. You start by specifying the caller function as async and then use await to handle the promise.

js

async function getResponse() {

const response = await fetch(

'https://carbonfootprint1.p.rapidapi.com/CarbonFootprintFromCarTravel?distance=100&vehicle=SmallDieselCar',

{

method: 'GET',

headers: {

'x-rapidapi-host': 'carbonfootprint1.p.rapidapi.com',

'x-rapidapi-key': 'your_api_key'

}

}

);

}

Because of the await keyword, the asynchronous function pauses until the promise is resolved. The Response object is assigned to response once the request completes.

Extracting Data

Although we have the Response object now, we can't access the data inside it right away. The response object returned by await fetch supports multiple functions for different data formats, which include:

  • response.json: Returns data as a JSON Object.
  • response.text: Returns data in raw text.
  • response.formData: Returns data as FormData.
  • response.blob: Returns data as a Blob Object.
  • response.arrayBuffer: Returns data as a Array Buffer Object.

All these functions return a promise which resolves into the specific data form. So we will use the await keyword again to extract the API response. Our code will take the following form:

js

async function getResponse() {

const response = await fetch(

'https://carbonfootprint1.p.rapidapi.com/CarbonFootprintFromCarTravel?distance=100&vehicle=SmallDieselCar',

{

method: 'GET',

headers: {

'x-rapidapi-host': 'carbonfootprint1.p.rapidapi.com',

'x-rapidapi-key': 'your_api_key'

}

}

);

const data = await response.json(); // Extracting data as a JSON Object from the response

}

Handling Errors

If the API request fails, we should handle the error and display an error message. With async/await, we can use the .ok() method to implement error handling:

js

async function getResponse() {

const response = await fetch(

'https://carbonfootprint1.p.rapidapi.com/CarbonFootprintFromCarTravel?distance=100&vehicle=SmallDieselCar',

{

method: 'GET',

headers: {

'x-rapidapi-host': 'carbonfootprint1.p.rapidapi.com',

'x-rapidapi-key': 'your_api_key'

}

}

);

if (!response.ok) {

throw new Error(`HTTP error! status: ${response.status}`);

}

const data = await response.json();

}

That is pretty much it. You are all set to use the Fetch API with async/await.

How to use the Fetch API with async/await (2024)
Top Articles
List of available trusted root certificates in macOS Sierra - Apple Support
Growth Equity Primer: Investment Strategy, Industry, & Career Path
Spectrum Gdvr-2007
Lengua With A Tilde Crossword
Craigslist St. Paul
His Lost Lycan Luna Chapter 5
PontiacMadeDDG family: mother, father and siblings
Martha's Vineyard Ferry Schedules 2024
Mcoc Immunity Chart July 2022
Noaa Swell Forecast
A Fashion Lover's Guide To Copenhagen
Tcu Jaggaer
Myql Loan Login
Oscar Nominated Brings Winning Profile to the Kentucky Turf Cup
Wisconsin Women's Volleyball Team Leaked Pictures
Accuradio Unblocked
Busted Barren County Ky
We Discovered the Best Snow Cone Makers for Carnival-Worthy Desserts
Kringloopwinkel Second Sale Roosendaal - Leemstraat 4e
BMW K1600GT (2017-on) Review | Speed, Specs & Prices
Wiseloan Login
55Th And Kedzie Elite Staffing
Hdmovie2 Sbs
Jackie Knust Wendel
Gma' Deals & Steals Today
John Philip Sousa Foundation
What is Software Defined Networking (SDN)? - GeeksforGeeks
Redbox Walmart Near Me
J&R Cycle Villa Park
Dtlr On 87Th Cottage Grove
15 Downer Way, Crosswicks, NJ 08515 - MLS NJBL2072416 - Coldwell Banker
Nail Salon Open On Monday Near Me
Rvtrader Com Florida
Graphic Look Inside Jeffrey Dresser
Memberweb Bw
LEGO Star Wars: Rebuild the Galaxy Review - Latest Animated Special Brings Loads of Fun With An Emotional Twist
How does paysafecard work? The only guide you need
The Ride | Rotten Tomatoes
El agente nocturno, actores y personajes: quién es quién en la serie de Netflix The Night Agent | MAG | EL COMERCIO PERÚ
Craigslist Summersville West Virginia
D-Day: Learn about the D-Day Invasion
Craigslist Putnam Valley Ny
Daly City Building Division
Author's Purpose And Viewpoint In The Dark Game Part 3
Homeloanserv Account Login
Jaefeetz
60 Days From May 31
Arcanis Secret Santa
3367164101
53 Atms Near Me
Hampton Inn Corbin Ky Bed Bugs
Latest Posts
Article information

Author: Golda Nolan II

Last Updated:

Views: 5677

Rating: 4.8 / 5 (58 voted)

Reviews: 81% of readers found this page helpful

Author information

Name: Golda Nolan II

Birthday: 1998-05-14

Address: Suite 369 9754 Roberts Pines, West Benitaburgh, NM 69180-7958

Phone: +522993866487

Job: Sales Executive

Hobby: Worldbuilding, Shopping, Quilting, Cooking, Homebrewing, Leather crafting, Pet

Introduction: My name is Golda Nolan II, I am a thoughtful, clever, cute, jolly, brave, powerful, splendid person who loves writing and wants to share my knowledge and understanding with you.