Asynchronous JavaScript and DOM Updates
In modern web applications, many tasks like fetching data from APIs, loading images, and processing large files are handled asynchronously to avoid blocking the user interface. In this section, you’ll learn how to work with asynchronous functions and how to update the DOM based on asynchronous operations.
Understanding Asynchronous JavaScript with Promises and async/await
Asynchronous code lets JavaScript run tasks in the background without blocking the main thread. Promise
objects represent eventual completion (or failure) of an async operation, while async/await
syntax simplifies writing asynchronous code.
-
Basic Promise Example
const fetchData = new Promise((resolve, reject) => {
setTimeout(() => {
const data = { user: "John", age: 25 };
resolve(data); // Simulates fetching data
}, 2000); // 2-second delay
});
fetchData.then((data) => {
console.log("Data fetched:", data);
}).catch((error) => {
console.error("Error fetching data:", error);
});Explanation: This Promise simulates a data-fetching delay of 2 seconds. If successful, the data is logged to the console; if an error occurs, it’s caught and logged.
-
Async/Await Syntax
async function getData() {
try {
const data = await fetchData; // Wait for the Promise to resolve
console.log("Data fetched:", data);
} catch (error) {
console.error("Error fetching data:", error);
}
}
getData();Explanation:
getData
is an asynchronous function that waits forfetchData
to complete. Theawait
keyword pauses the function until the Promise resolves.
Fetching Data from an API and Updating the DOM
With asynchronous functions, you can fetch live data from an API and update the DOM based on the retrieved information.
-
Example: Fetching Data from a JSON Placeholder API
<button id="load-user">Load User</button>
<div id="user-info"></div>const loadUserButton = document.getElementById("load-user");
const userInfo = document.getElementById("user-info");
loadUserButton.addEventListener("click", async () => {
try {
const response = await fetch("https://jsonplaceholder.typicode.com/users/1");
const user = await response.json(); // Parse JSON data
userInfo.innerHTML = `
<p><strong>Name:</strong> ${user.name}</p>
<p><strong>Email:</strong> ${user.email}</p>
<p><strong>City:</strong> ${user.address.city}</p>
`;
} catch (error) {
userInfo.textContent = "Error loading user data.";
console.error("Error:", error);
}
});Explanation: When "Load User" is clicked, the function fetches user data from the JSONPlaceholder API and updates the
user-info
div with the user’s name, email, and city.