Fetch api and async await in javascript
// Select the DOM element where the product list will be rendered
const list = document.querySelector('.list');
// Define an asynchronous function to fetch and handle product data
async function getListofProductData() {
try {
// Fetch data from the API endpoint
const response = await fetch('https://dummyjson.com/products', {
method: 'GET', // HTTP method for the request
});
// Convert the response to JSON
const result = await response.json();
// Log the result for debugging purposes
console.log(result);
// Check if result and result.products are defined and if there are products
if (result && result.products && result.products.length) {
// Call the renderProducts function to display the products
renderProducts(result.products);
}
} catch (e) {
// Log any errors that occur during the fetch or processing
console.log(e);
}
}
// Function to render product data into the DOM
function renderProducts(products) {
// Create HTML content for each product and insert it into the 'list' element
list.innerHTML = products.map(product => `
<div>
<h2>${product.title}</h2> <!-- Product title -->
<p>${product.description}</p> <!-- Product description -->
<p>Price: $${product.price}</p> <!-- Product price -->
<p>Brand: ${product.brand}</p> <!-- Product brand -->
</div>
`).join(''); // Join all product HTML strings into a single string
}
// Call the function to fetch and render product data
getListofProductData();