Promises and Asynchronous JavaScript
Learning Objectives
- Understand why asynchronous code is needed
- Learn the Promise object and its states
- Chain async operations with
.then()and.catch() - Use
Promise.all()and related helpers - Prepare for
fetch()andasync/await
Section 22.1: Why Promises Exist
What Problem Do They Solve?
Asynchronous work happens after the current code finishes, so we need a clean way to handle results later.
Promise States
// A Promise can be in one of three states:
// pending -> waiting
// fulfilled -> completed successfully
// rejected -> failed
Creating a Promise
let promise = new Promise((resolve, reject) => {
let success = true;
if (success) {
resolve("Task completed");
} else {
reject("Task failed");
}
});
promise
.then(result => console.log(result))
.catch(error => console.error(error));
Section 22.2: Chaining Promises
Working Step by Step
function getUser() {
return Promise.resolve({ id: 1, name: "Alice" });
}
function getPosts(userId) {
return Promise.resolve([
{ id: 1, userId, title: "First post" },
{ id: 2, userId, title: "Second post" }
]);
}
getUser()
.then(user => getPosts(user.id))
.then(posts => console.log(posts))
.catch(error => console.error(error));
Error Handling
fetchData()
.then(data => processData(data))
.then(result => saveResult(result))
.catch(error => {
console.error("Something went wrong:", error);
});
Section 22.3: Promise Helpers
Promise.all()
Promise.all([
fetchUser(),
fetchPosts(),
fetchComments()
])
.then(([user, posts, comments]) => {
console.log(user, posts, comments);
})
.catch(error => console.error(error));
Promise.allSettled()
Promise.allSettled([
fetchUser(),
fetchPosts(),
fetchComments()
]).then(results => {
console.log(results);
});
Promise.race()
Promise.race([
slowRequest(),
fastRequest()
]).then(winner => {
console.log("First result:", winner);
});
Section 22.4: Promises and Async/Await
Async/Await Uses Promises
async function loadData() {
try {
let result = await Promise.resolve("Ready");
console.log(result);
} catch (error) {
console.error(error);
}
}
loadData();
Coding Challenges
Challenge 22.1: Delayed Greeting
Task: Return a Promise that resolves after a delay and prints a greeting
Challenge 22.2: Promise Chain
Task: Build a 3-step Promise chain with error handling
Challenge 22.3: Parallel Tasks
Task: Use Promise.all() to run multiple tasks together
Key Takeaways
✅ Promises represent future values
✅ .then() handles success
✅ .catch() handles errors
✅ Promise.all() combines multiple async tasks
✅ fetch() returns a Promise
Quiz Questions
- What are the three Promise states?
- What does
resolve()do? - What does
reject()do? - What is the difference between
.then()and.catch()? - Why are Promises useful before using
fetch()?
Next Module: Module 23 - Query a Web Server