Fetching Data with Fetch API | Javascript

 fetch('https://api.example.com/data')
    .then(response => response.json())
    .then(data => {
        // Handle the data
    })
    .catch(error => {
        // Handle errors
    });
 

AI Explanation

This code snippet uses the Fetch API to make a network request to 'https://api.example.com/data'. Here's an explanation of each part of the code: 1. `fetch('https://api.example.com/data')`: This initiates a GET request to the specified URL ('https://api.example.com/data') to fetch data from the server. 2. `.then(response => response.json())`: This Promise is chained to the fetch call. It receives the response from the server and asynchronously parses it as JSON. This is done with the `json()` method, which returns a Promise that resolves with the parsed JSON data. 3. `.then(data => { // Handle the data })`: This Promise is chained to the previous `.then()` handler. It receives the parsed JSON data as a parameter and allows you to handle it within the function inside the curly braces. Here, you can manipulate, display, or work with the retrieved data as needed. 4. `.catch(error => { // Handle errors })`: This is a catch block that handles any errors that may occur during the fetch request, parsing of the response, or handling of the data. If any error occurs at any stage in the Promise chain, it will be caught here, allowing you to handle the error appropriately. In summary, this code snippet fetches data from an API, parses the response as JSON, handles the data if the request is successful, and catches and handles any errors that may occur during the process.