Promises & Async/AwaitBeginner
1Question 1 of 1
javascriptHow do Promises work and how does async/await simplify asynchronous control flow?
Explanation & Concept
A Promise is an object representing the eventual completion or failure of an asynchronous operation, existing in one of three states: `pending`, `fulfilled`, or `rejected`.
`async/await` is syntactic sugar built on top of Promises and generators. An `async` function always returns a Promise. The `await` keyword pauses function execution until the awaited Promise settles, allowing asynchronous code to be read and written sequentially with standard `try/catch` error handling.
Code Example
javascript
// Helper that simulates an async network fetch
const fetchUserData = (userId) => {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (userId > 0) resolve({ id: userId, name: "Alex" });
else reject(new Error("Invalid User ID"));
}, 500);
});
};
async function loadProfile(id) {
try {
console.log("Fetching user...");
const user = await fetchUserData(id); // Pauses until resolved
console.log("User retrieved:", user.name);
return user;
} catch (error) {
console.error("Failed to load user:", error.message);
} finally {
console.log("Operation finished.");
}
}
loadProfile(1);How It Works & Key Takeaways
`await` unwraps the resolved Promise value directly into `user`. If the Promise rejects, execution jumps straight to the `catch` block, eliminating messy `.then().catch()` nesting.
Mock Test · 1 Questions · Optional
Ready for Prototypal Inheritance?
Take a quick test to evaluate yourself, or move straight to the next module.
Beginner1 questions