Next →

Fetching Data from APIs in JavaScript

JavaScript provides the fetch API to make network requests and work with external data sources.

Basic Fetch Usage

You can fetch data from a URL and handle the response using promises.

Example: Fetch user data from a placeholder API

fetch('https://jsonplaceholder.typicode.com/users/1')
  .then(response => response.json())
  .then(data => {
    console.log(data.name);
  })
  .catch(error => {
    console.error('Error:', error);
  });

Async/Await Syntax

You can also use async functions for cleaner, easier-to-read asynchronous code.

async function getUser() {
  try {
    const response = await fetch('https://jsonplaceholder.typicode.com/users/1');
    const data = await response.json();
    console.log(data.name);
  } catch (error) {
    console.error('Error:', error);
  }
}
getUser();