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();


Post a Comment

Cookie Consent
We serve cookies on this site to analyze traffic, remember your preferences, and optimize your experience.
Oops!
It seems there is something wrong with your internet connection. Please connect to the internet and start browsing again.
AdBlock Detected!
We have detected that you are using adblocking plugin in your browser.
The revenue we earn by the advertisements is used to manage this website, we request you to whitelist our website in your adblocking plugin.
Site is Blocked
Sorry! This site is not available in your country.