Lesson 32 / 38
Promises
A cleaner way to represent a future value.
Creating & consuming
resolve fulfills the promise, reject fails it; .then() and .catch() react to each outcome.
const promise = new Promise((resolve, reject) => {
setTimeout(() => resolve("Done!"), 1000);
});
promise.then((result) => console.log(result))
.catch((err) => console.log(err));Three states
A Promise is pending, then settles as fulfilled or rejected — once settled, it never changes state again.
Chaining
Each .then() returns a new promise, so async steps can be chained in a flat, readable sequence.
fetchUser()
.then((user) => fetchPosts(user.id))
.then((posts) => console.log(posts))
.catch((err) => console.error(err));Quick check: What does .catch() handle in a Promise chain?
- Only network errors
- Any rejection from earlier in the chain
- Nothing — it's just for logging
Answer
Any rejection from earlier in the chain — A rejection at any earlier .then() skips the remaining .then() calls and jumps straight to the nearest .catch().