Handle asynchronous operations elegantly with Promises and async/await syntax.
1// Creating a Promise2const fetchUser = new Promise((resolve, reject) => {3 const success = true;4 setTimeout(() => {5 if (success) {6 resolve({ name: "Alice", role: "Developer" });7 } else {8 reject("User not found");9 }10 }, 1000);11});12 13// Consuming a Promise14fetchUser15 .then(user => console.log(user.name)) // Alice16 .catch(err => console.error(err));Alice
1async function getUserData(userId) {2 try {3 const response = await fetch(`/api/users/${userId}`);4 const data = await response.json();5 console.log(data.name);6 return data;7 } catch (error) {8 console.error("Failed to fetch user:", error);9 }10}11 12// Using await with multiple operations13async function loadDashboard() {14 const [user, posts] = await Promise.all([15 fetch("/api/user").then(r => r.json()),16 fetch("/api/posts").then(r => r.json()),17 ]);18 console.log(`${user.name} has ${posts.length} posts`);19}