"Handling Errors in Async/Await Functions: A Practical Guide with UI Example"

// Async function to simulate fetching data
async function fetchData() {
  return new Promise((resolve, reject) => {
      // Simulating a network request
      setTimeout(() => {
          const randomNumber = Math.random();
          console.log(randomNumber)
          if (randomNumber < 0.5) {
              // Reject with an error if random number is less than 0.5
              reject(new Error("Failed to fetch data"));
          } else {
              resolve("Data fetched successfully");
          }
      }, 1000);
  });
}

// Function to display result
function displayResult(message) {
  const resultDiv = document.getElementById("result");
  resultDiv.textContent = message;
}

// Event listener for button click
document.getElementById("fetchDataBtn").addEventListener("click", async () => {
  try {
      const data = await fetchData();
      displayResult(data);
  } catch (error) {
      displayResult("Error: " + error.message);
  }
});
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Error Handling with Async/Await</title>
    <link rel="stylesheet" href="styles.css">
</head>
<body>
    <div class="container">
        <h1>Error Handling with Async/Await</h1>
        <button id="fetchDataBtn">Fetch Data</button>
        <div id="result"></div>
    </div>
    <script src="script.js"></script>
</body>
</html>
.container {
  text-align: center;
  margin-top: 50px;
}

button {
  padding: 10px 20px;
  font-size: 16px;
  cursor: pointer;
}

#result {
  margin-top: 20px;
}

Code explanation

Async Function to Fetch Data:

The fetchData() function is marked as async, indicating that it will always return a Promise.

  • Inside fetchData(), a Promise is created using the Promise constructor. This Promise simulates an asynchronous operation using setTimeout() to mimic a network request.

Event Listener for Button Click:

An event listener is added to the button with the id "fetchDataBtn".

  • When the button is clicked, an anonymous async arrow function is executed.

  • Inside this function, there's a try...catch block. This is where error handling occurs for asynchronous operations.

  • Within the try block, await is used to wait for the fetchData() function to complete. This means that the code will pause execution at this line until the Promise returned by fetchData() resolves or rejects.

  • If fetchData() resolves successfully, the result is stored in the data variable and then displayed using the displayResult() function.

  • If fetchData() rejects with an error, the error is caught in the catch block, and an error message is displayed in the result container.

In summary, async functions allow you to write asynchronous code that looks synchronous and easier to understand, while await pauses the execution of code until a Promise is settled. This makes error handling in asynchronous code more straightforward and readable..