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();
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter