Promises: then, catch & chaining
Master the modern foundation of asynchronous JavaScript. Learn how Promises flatten the pyramid of doom and make background tasks predictable.
The IOU of JavaScript
A **Promise** is an object that represents the eventual completion (or failure) of an asynchronous operation. Think of it like a restaurant buzzer: you place your order, you receive a buzzer (the Promise), and you can continue talking with your friends until the buzzer goes off.
A Promise is always in one of three states:
1. pending: The initial state. The background task is still running.
2. fulfilled: The task completed successfully.
3. rejected: The task failed (e.g., a network error).
Flattening the Pyramid
Promises were introduced in ES6 (2015) specifically to fix Callback Hell.
Instead of nesting functions deep inside one another, Promises allow you to attach callbacks to the returned object using .then() for success and .catch() for errors.
This structural change pulls your code back to the left margin and centralizes your error handling.
The Power of Chaining
The true magic of a Promise is that **every .then() returns a brand new Promise**.
This means you can chain them together. If you return a value inside a .then(), that exact value is passed down as the argument to the very next .then() in the chain.
If an error occurs anywhere in the chain, execution immediately skips down to the nearest .catch(), ignoring all the .then() blocks in between.
The Promise Chain
Click 'Fetch Data' to watch a Promise transition from pending to fulfilled, and see how the resolved value is modified and passed down the .then() chain.
The Promise Chain
fetch("/api/user")
console.log(data.name);
})
console.error("Network Failed");
});
Check yourself
Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.
Remember this
- A Promise represents the future result of an asynchronous operation.
- A Promise has three states: pending, fulfilled, and rejected.
- Once a Promise is settled (fulfilled or rejected), its state is locked forever.
- You attach a
.then()to handle a successful fulfillment, and a.catch()to handle a rejection. - Every
.then()returns a new Promise, allowing you to chain them sequentially. - A single
.catch()at the end of a chain will catch an error from anywhere in the chain.
Done with this concept?
Mark it complete to track your progress. No login needed.