async await fetch api in javascript

To use the Fetch API asynchronously with async/await in JavaScript, you need to follow these steps:

  1. Define an async function that will make the Fetch API call.
  2. Inside this async function, make the Fetch API call using the await keyword.
  3. Create a Response object from the fetch request.
  4. Use the json() method on the Response object to extract data from the response into JSON format.
  5. Return the JSON data from the async function.

Here's an example of how to make an asynchronous Fetch API call using async/await:

index.tsx
async function fetchData() {
  try {
    const response = await fetch('https://jsonplaceholder.typicode.com/todos/1');
    const data = await response.json();
    console.log(data);
  } catch (error) {
    console.log(error);
  }
}

fetchData();
246 chars
12 lines

In this example, we're using the fetch() method to make a GET request to the JSONPlaceholder API, which will respond with a single TODO item. We're then using await to pause the execution of the async function while the response is being fetched. Once the response is received, we're using the json() method to extract the JSON data from it. Finally, we're logging the data to the console.

Note: using async/await with fetch API is supported in modern browsers.

gistlibby LogSnag