0
0
JavascriptHow-ToBeginner · 3 min read

How to Use Async Await with Fetch in JavaScript

Use async before a function to make it asynchronous, then use await before fetch() to wait for the HTTP request to complete. This lets you write asynchronous code that looks like normal, easy-to-read code.
📐

Syntax

The async keyword makes a function return a promise and allows the use of await inside it. The await keyword pauses the function execution until the promise resolves, such as waiting for fetch() to get a response.

Basic syntax:

  • async function functionName() { ... } - declares an async function.
  • const response = await fetch(url); - waits for the fetch call to finish.
  • const data = await response.json(); - waits to parse the response as JSON.
javascript
async function getData() {
  const response = await fetch('https://api.example.com/data');
  const data = await response.json();
  return data;
}
💻

Example

This example fetches JSON data from a public API and logs the result. It shows how async and await make the code easy to read and write.

javascript
async function fetchUser() {
  try {
    const response = await fetch('https://jsonplaceholder.typicode.com/users/1');
    if (!response.ok) {
      throw new Error('Network response was not ok');
    }
    const user = await response.json();
    console.log(user);
  } catch (error) {
    console.error('Fetch error:', error);
  }
}

fetchUser();
Output
{ id: 1, name: 'Leanne Graham', username: 'Bret', email: 'Sincere@april.biz', ... }
⚠️

Common Pitfalls

Common mistakes include forgetting to use async before the function, which causes await to fail, or not handling errors with try/catch. Also, fetch() only rejects on network errors, so always check response.ok to catch HTTP errors.

javascript
/* Wrong: missing async keyword */
function getData() {
  const response = await fetch('https://api.example.com/data'); // SyntaxError
}

/* Right: async function with try/catch */
async function getData() {
  try {
    const response = await fetch('https://api.example.com/data');
    if (!response.ok) {
      throw new Error('HTTP error ' + response.status);
    }
    const data = await response.json();
    return data;
  } catch (error) {
    console.error('Error fetching data:', error);
  }
}
📊

Quick Reference

Remember these tips when using async/await with fetch:

  • Always mark functions using await with async.
  • Use try/catch to handle errors gracefully.
  • Check response.ok to detect HTTP errors.
  • Use await response.json() to parse JSON responses.

Key Takeaways

Use async before functions to enable await inside them.
Use await with fetch() to wait for the HTTP response.
Always check response.ok to handle HTTP errors.
Wrap await calls in try/catch to catch errors.
Parse JSON responses with await response.json().