JSFiddle - React, Tailwind, and code Playground

by dshilkret

JavaScript

function fetchData(success) {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            if (success) {
                resolve("Data retrieved successfully!");
            } else {
                reject("Failed to retrieve data.");
            }
        }, 2000); // Simulate a delay of 2000 milliseconds (2 seconds)
    });
}

// Use the fetchData function
fetchData(true)
    .then(data => {
        console.log(data); // Logs: Data retrieved successfully!
        return fetchData(false); // Attempt to fetch again, this time expecting failure
    })
    .then(secondData => {
        console.log(secondData); // This line will not be executed due to the error
    })
    .catch(error => {
        console.error(error); // Logs: Failed to retrieve data.
    });