fetching multple data endpoints

PHOTO EMBED

Mon Sep 09 2024 05:36:26 GMT+0000 (Coordinated Universal Time)

Saved by @davidmchale #fetch #endpoint #data

async function fetchData(url) {
  try {
    const response = await fetch(url);
    if (!response.ok) {
      throw new Error(`Error: ${response.status} ${response.statusText}`);
    }
    const data = await response.json(); // Parse and return JSON data
    return data;
  } catch (error) {
    console.error('Fetch failed:', error.message);
    throw error; // Re-throw the error if necessary for handling elsewhere
  }
}

async function useData() {
  try {
    const data1 = await fetchData('https://jsonplaceholder.typicode.com/posts/1');
    console.log('First Request Data:', data1);
  
    // If you need to fetch data from another endpoint:
    const data2 = await fetchData('https://jsonplaceholder.typicode.com/posts/2');
    console.log('Second Request Data:', data2);
  } catch (error) {
    console.error('Error in data retrieval:', error);
  }
}

useData();
content_copyCOPY