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
Most Expensive Domains Ever Sold
YOLO And The FIRE Movement: Why It Doesn’t Work (Yet)
Davita Internet
Ffxiv Palm Chippings
Research Tome Neltharus
Valley Fair Tickets Costco
Mohawkind Docagent
Emmalangevin Fanhouse Leak
Mndot Road Closures
Erskine Plus Portal
13 The Musical Common Sense Media
World Cup Soccer Wiki
Craigslist Heavy Equipment Knoxville Tennessee
Edible Arrangements Keller
Slag bij Plataeae tussen de Grieken en de Perzen
Oscar Nominated Brings Winning Profile to the Kentucky Turf Cup
Love In The Air Ep 9 Eng Sub Dailymotion
Leader Times Obituaries Liberal Ks
Committees Of Correspondence | Encyclopedia.com
Huntersville Town Billboards
Timeforce Choctaw
Ford F-350 Models Trim Levels and Packages
Routing Number For Radiant Credit Union
Bn9 Weather Radar
City Of Durham Recycling Schedule
Urbfsdreamgirl
Truvy Back Office Login
Table To Formula Calculator
Sandals Travel Agent Login
Orange Park Dog Racing Results
Neteller Kasiinod
Maths Open Ref
DIY Building Plans for a Picnic Table
Have you seen this child? Caroline Victoria Teague
Steven Batash Md Pc Photos
Tamil Play.com
Atlantic Broadband Email Login Pronto
Spinning Gold Showtimes Near Emagine Birch Run
Oreillys Federal And Evans
Asian Grocery Williamsburg Va
Afspraak inzien
Directions To 401 East Chestnut Street Louisville Kentucky
Academic important dates - University of Victoria
Gpa Calculator Georgia Tech
Housing Intranet Unt
T&Cs | Hollywood Bowl
St Vrain Schoology
Online College Scholarships | Strayer University
Nurses May Be Entitled to Overtime Despite Yearly Salary
Understanding & Applying Carroll's Pyramid of Corporate Social Responsibility
Unpleasant Realities Nyt
Tyrone Unblocked Games Bitlife
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.