All 28 lessons ▾
Inside JavaScript · Lesson 21 of 28
Promises: What They Really Are
So a promise is JavaScript's way of saying, I don't have the answer yet, but I will. So let's see what a promise really is, from the inside.
A new lesson goes up every day at 11 am. Subscribe on YouTube so you don't miss it.
Got a doubt? Ask in the comments under the video.Subscribe
- A promise: a placeholder for a future value
- You attach callbacks with then, not pass them
- Pending, then fulfilled or rejected, only once
- Promises are immutable
- Chaining fixes callback hell: return in every then
- fetch returns a promise
Part 1From callbacks to promises
So in the last episode, we saw the dark side of callbacks. Callback hell, and inversion of control. So today, we fix both, with promises. Promises are how JavaScript handles async operations today. They're in every fetch call, every API, every library. And if you're preparing for a frontend interview, promise questions are almost guaranteed. So this episode is a little longer, and it's worth every minute. Let's understand promises properly, from the inside.
1const seats = ["A1", "A2"];2 3// before: we pass our function in4api.bookSeats(seats, function (booking) {5 api.makePayment(booking);6});So here's our movie ticket code from last time. We pass the payment step into bookSeats, and trust bookSeats to call it. But bookSeats may be written by another team, another company, or an intern on their first day. What if it never calls our function? Or calls it twice, and we pay twice? That's the problem, remember? Inversion of control. Our most important code is in someone else's hands. So now what if bookSeats didn't take our function at all?
1// after: bookSeats gives us a promise2const booking = api.bookSeats(seats);3 4booking.then(function (result) {5 api.makePayment(result);6});So with promises, bookSeats doesn't take a callback anymore. Instead, it immediately gives us back something, called a promise. For now, think of it as an empty object, which gets filled with the booking later. We store it in booking. And then, we attach our function to it ourselves, using .then. Now you might say, wait! We're still writing a callback function here. This looks even more complicated! So what did we gain? Listen to the difference carefully. Before, we were passing our function to someone else. Now, we're attaching our function to a promise. So our code stays with us.
So remember this. With callbacks, you pass your function away, and hope. With promises, you attach your function to a promise object, and the promise guarantees two things. It will call your function when the result is ready. And it will call it only once. Never twice, never too early. So that's how promises fix inversion of control.
Part 2What is a promise, really?
But what exactly is this promise that bookSeats gave us? So let's look inside it, step by step.
1const booking = api.bookSeats(seats);2console.log(booking);3 4booking.then(function (ticket) {5 console.log("Booked:", ticket);6});Promise {<pending>}
Booked: T-42Line one calls bookSeats. It starts talking to the server, and instantly returns a promise. Now look at memory. booking is a promise, and inside it, the state is pending, and the result is undefined. Just like DevTools shows it. Line two logs it, and the console prints promise, pending. JavaScript doesn't wait. Line four attaches our function with then. Now, two seconds later, the server answers. The promise fills itself with the result, ticket T forty two, and its state becomes fulfilled. And automatically, our attached function runs, and the console shows booked, T forty two.
So what is a promise? Think of it as a placeholder for a value that will come in the future. Like a token at a food court. So you order, and you get a token right away. The food isn't ready yet, but you have the token. When the food is ready, your number is called, and you collect it. So the token is the promise, and the food is the result.
Now every promise is in one of three states. It starts as pending. Then, if the work succeeds, it becomes fulfilled, and holds the result. If the work fails, say the server is down, it becomes rejected, and holds the error. And now here's the important part. A promise settles only once. Once it's fulfilled or rejected, it can never change again. No going back to pending, and no switching from success to failure.
Part 3A real promise
So enough theory. Let's look at a real promise, in the browser.
1const URL = "https://api.github.com/users/octocat";2const user = fetch(URL);3 4console.log(user);5// Promise {<pending>}6// [[PromiseState]]: "fulfilled"7// [[PromiseResult]]: ResponseSo fetch is a Web API that makes a network request, and it returns a promise. Here, we ask GitHub's public API for a user. Log it, and the console shows promise, pending. Now expand it, and look inside. You'll see two hidden properties. PromiseState, and PromiseResult. And here's a funny Chrome quirk. The log said pending, but when you expand it, the state already says fulfilled! That's because Chrome shows you the live object, which has finished by the time you click. So don't let that confuse you.
1user.then(function (response) {2 console.log(response.status); // 2003 return response.json();4});Now to use the result, we attach a function with then. When the response arrives, our function receives it. Here, response.status is two hundred, which means success. The actual data arrives as a stream, inside the body. To read it, we call response.json, which, surprise, returns another promise. Promises everywhere! So we'll chain these properly in the next episode.
1const user = fetch(URL);2 3console.log(user.status); // undefined4 5user.then(function (response) {6 console.log(response.status); // 2007});And now here's a mistake almost every beginner makes. They try to read the value straight from the promise. user.status gives undefined. Why? Because user is not the response. It's the promise, the token. The response lives inside it, and it may not even have arrived yet. So the only way to get it out is then. Inside then, response.status is two hundred. So remember, a promise is a container for the value, not the value itself.
Now one more important property. A promise object is immutable. Once it has its result, nobody can change that result from outside. So you can pass the user promise anywhere in your program, to any function, and no one can tamper with it. The only way to get the value is to attach a function with then. So that makes promises very safe to share.
Part 4Goodbye, pyramid of doom
So promises fixed inversion of control. Now let's fix callback hell too.
1api.bookSeats(seats, function (booking) {2 api.makePayment(booking, function (payment) {3 api.sendTicket(payment, function (ticket) {4 api.addRewards(ticket, function () {5 console.log("All done!");6 });7 });8 });9});So here's the pyramid from last episode. Book the seats, then pay, then send the ticket, then add the rewards. Each step lives inside the one before it, so the code grows sideways, not down. Just four steps, and it's already hard to follow. Now, what if each of these functions returned a promise instead?
1api.bookSeats(seats)2 .then(function (booking) {3 return api.makePayment(booking);4 })5 .then(function (payment) {6 return api.sendTicket(payment);7 })8 .then(function (ticket) {9 return api.addRewards(ticket);10 })11 .then(function () {12 console.log("All done!");13 });So here it is. Each step returns a promise, so we can attach the next then right after it. And notice, we don't even need a variable for the promise. We put .then straight after the call. Book the seats, then make the payment, then send the ticket, then add rewards. Now look at the shape. It goes down, not sideways. Every step at the same level. So this is called promise chaining. Each then waits for the one before it, and receives its result.
1api.bookSeats(seats)2 .then(function (booking) {3 api.makePayment(booking); // forgot return!4 })5 .then(function (payment) {6 console.log(payment); // undefined7 });But now here's the most common mistake with chaining. Look at the first then. It calls makePayment, but we forgot to return it. So that then returns nothing, which means undefined. And the next then gets undefined as payment! Worse, it doesn't even wait for the payment to finish. So always remember. Whatever you return from one then becomes the input of the next one. Return your promises!
1api.bookSeats(seats)2 .then((booking) => api.makePayment(booking))3 .then((payment) => api.sendTicket(payment))4 .then((ticket) => api.addRewards(ticket))5 .then(() => console.log("All done!"));And with arrow functions, the chain becomes beautiful. When an arrow function has just one expression, it returns it automatically, so you can't forget the return. Five lines, top to bottom, reading like a story. Book, pay, send, reward, done. Now some developers love this short style, and some prefer the function keyword. So both work exactly the same, so pick the one that reads best to you.
1api.bookSeats(seats)2 .then((booking) => api.makePayment(booking))3 .then((payment) => api.sendTicket(payment))4 .catch(function (err) {5 console.log("Something failed:", err.message);6 });Now what if a step fails? Say the payment is declined. With promises, one catch at the end of the chain handles an error from any step above it. Now compare that with callback hell, where every single level needed its own error check. One catch, and the whole chain is protected. So we'll go deep into errors, and how they flow through a chain, in the next episode.
1console.log("A");2const p = fetch("https://api.github.com/users/octocat");3console.log(p);4p.then(function () {5 console.log("B");6});7console.log("C");What's the order?
Show the answer
So A first. Then fetch returns a pending promise instantly, so the next line logs promise, pending. Then C, because JavaScript doesn't wait. And only when the response arrives, our function runs, and prints B. So A, the pending promise, C, B. Did you get it?
Two questions, answered in the comments, in your own words. One, what is a promise? Two, why do we use promises? Don't read the other comments first. Write your own answer. It takes five minutes, and it locks this episode in your head.
Show the answer
One, what is a promise? An object that represents the eventual completion, or failure, of an asynchronous operation. It starts pending, and settles only once: fulfilled with a value, or rejected with an error.
Two, why do we use promises? To fix the two problems of callbacks.
- No inversion of control: we don't pass our function into someone else's code. We attach it with
then, and the promise calls it exactly once. - No callback hell:
thenreturns a new promise, so the steps run as a flat chain instead of a pyramid, with onecatchfor every error.
Try it first, then post yours in the comments under the video.
The video on YouTube, and the lesson as a swipe-through on Instagram.