All 28 lessons ▾
Inside JavaScript · Lesson 22 of 28
Make Your Own Promise: Chaining and Error Handling
So far, we've used promises that others made. So today, we make our own, chain them properly, and handle errors like a pro.
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
- new Promise gives you resolve and reject
- resolve fulfils, reject rejects, only once
- Always end a chain with catch
- A returned value or promise flows to the next then
- Errors skip to the nearest catch
- finally runs either way
Part 1Making a promise
So in the last episode, bookSeats gave us a promise, and we used it with then. That's called consuming a promise. But someone had to create that promise. So today, we become that someone. We'll write the producer side, chain promises properly, and handle errors the right way. And by the end, you'll write your own promises with full confidence.
So to create a promise, JavaScript gives us the Promise constructor. You write new Promise, and pass it a function. Now JavaScript runs that function immediately, and gives it two functions of its own. resolve, and reject. When your work succeeds, call resolve, with the result. When it fails, call reject, with an error. That's the whole contract.
1function bookSeats(seats) {2 return new Promise(function (resolve, reject) {3 if (seats.length > 10) {4 reject(new Error("Too many seats"));5 return;6 }7 const bookingId = "BK-101"; // from the server8 resolve(bookingId);9 });10}So here's our own bookSeats. It returns a new promise. Inside, we validate first. If someone tries to book more than ten seats, we call reject, with a new error, too many seats. And we return, to stop right there. Otherwise, the server gives us a booking ID, and we call resolve with it. Now notice the return after reject. A promise settles only once, so a later resolve would be ignored anyway. But returning early makes the code clear, and skips work that isn't needed.
1function bookSeats(seats) {2 return new Promise(function (resolve, reject) {3 setTimeout(function () {4 resolve("BK-101");5 }, 2000);6 });7}8 9const p = bookSeats(["A1", "A2"]);10console.log(p);11p.then(function (id) {12 console.log("Booked:", id);13});Promise {<pending>}
Booked: BK-101Now let's watch a promise being made, with a timer pretending to be the server. Phase one stores bookSeats. Line nine calls it. Inside, line two creates a new promise, and JavaScript runs our function straight away, giving it resolve and reject. Line three starts a two second timer, as our fake server. And bookSeats returns the promise immediately. So p is a promise, pending, with no result yet. Line ten prints promise, pending. Line eleven attaches our function with then. Now, two seconds later, the timer fires, and line four calls resolve with BK one zero one. That's the moment the promise becomes fulfilled, with that result. And our then function runs, printing booked, BK one zero one.
So remember this. The moment you call resolve, the promise becomes fulfilled, and every then attached to it runs, with that value. The moment you call reject, the promise becomes rejected, and catch runs instead, with the error. And whichever happens first wins. So after that, the promise never changes.
1function wait(ms) {2 return new Promise(function (resolve) {3 setTimeout(resolve, ms);4 });5}6 7wait(1000).then(function () {8 console.log("One second later!");9});And now here's a tiny promise you'll use again and again. wait. It takes a number of milliseconds, and returns a promise that resolves after that time. Inside, we just hand resolve itself to setTimeout, as the callback. So wait of one thousand gives a promise that's fulfilled after one second, and then our function prints, one second later. Now this trick is called promisifying. Wrapping an old callback API inside a promise, so the rest of your code can use then.
Part 2Handling errors
Now let's look at the failure side. What happens when a promise is rejected? Let's see.
1bookSeats(new Array(12))2 .then(function (id) {3 console.log("Booked:", id);4 })5 .catch(function (err) {6 console.log("Oops:", err.message);7 });8// Oops: Too many seatsSo here, someone tries to book twelve seats. bookSeats calls reject. So the then is skipped completely, and the catch runs, with the error. It prints, oops, too many seats. So the user sees a friendly message, and your app keeps working.
1bookSeats(new Array(12))2 .then(function (id) {3 console.log("Booked:", id);4 });5 6// Uncaught (in promise) Error: Too many seatsBut now what if we forget the catch? Then the rejection has nowhere to go. The browser shows a scary red error in the console. Uncaught, in promise, too many seats. And your user sees nothing at all. The button just does nothing, and they have no idea why. And in Node.js, an unhandled rejection can even crash your whole server. So remember this golden rule. It's very important. Every promise chain should end with a catch.
Part 3Chaining, properly
Now, let's connect several promises together, and see exactly how values, and errors, flow through a chain.
1bookSeats(["A1", "A2"])2 .then(function (id) {3 console.log("Booked:", id);4 return id;5 })6 .then(function (id) {7 return makePayment(id);8 })9 .then(function (payment) {10 console.log(payment);11 })12 .catch(function (err) {13 console.log("Oops:", err.message);14 });So here's the rule of chaining. Whatever you return from a then becomes the input of the next then. The first then logs the booking ID, and returns it. A plain value. So the next then receives the same ID. This one returns a promise, from makePayment. Now when you return a promise, the chain waits for it to settle, and passes its result on. So the third then receives the payment details. One chain, values flowing down, step by step.
1function makePayment(id) {2 return new Promise(function (resolve, reject) {3 resolve("Payment done for " + id);4 });5}And makePayment is just another promise we create ourselves. For now, it resolves straight away, with a message, payment done for BK one zero one. In real life, it would talk to a payment gateway. But the shape is always the same. Return a new promise, then resolve or reject. And now for a promise that's already done, there's a shortcut. Promise.resolve, with a value, gives you an already fulfilled promise. And Promise.reject gives you an already rejected one.
1bookSeats(["A1", "A2"])2 .then(function (id) {3 return makePayment(id).then(function (payment) {4 return sendTicket(payment).then(function (ticket) {5 console.log(ticket);6 });7 });8 });And now watch out for this one. Some people put each then inside the previous one. It works. But look at the shape. It's growing sideways again! That's promise hell, callback hell in a promise costume. So the fix is simple. Return the promise, and handle its result at the next level of the chain. One then after another, all at the same level, flat and readable.
And errors? They flow down too, but they skip. So say bookSeats works, but makePayment rejects, because the card was declined. The next step, sendTicket, is skipped. And everything after it. The error falls straight down to the nearest catch. So one catch at the end protects every step above it. No more error checks at every level, like in callback hell.
1bookSeats(["A1", "A2"])2 .then(function (id) {3 if (id === "") {4 throw new Error("Empty booking ID");5 }6 return makePayment(id);7 })8 .catch(function (err) {9 console.log("Oops:", err.message);10 });Now here's a rule many people don't know. If you throw an error inside a then, it doesn't crash your program. JavaScript turns it into a rejection. So here, if the booking ID comes back empty, we throw a new error, and the chain treats it exactly like a reject. It skips straight to the catch, which prints, oops, empty booking ID. So inside a chain, throwing is just another way of saying, this step failed.
1bookSeats(["A1", "A2"])2 .then(function (id) {3 return addRewards(id);4 })5 .catch(function (err) {6 console.log("No rewards today:", err.message);7 })8 .then(function () {9 console.log("Enjoy the movie!");10 });But sometimes, you want the chain to continue even after an error. Say adding reward points fails. That's not a big deal. The user should still get their movie! So put a catch in the middle. A catch only handles errors from the steps above it. After it handles one, the chain continues as normal. So even if rewards fail, we still print, enjoy the movie. Now you can even use several catches, one guarding each part of the chain, plus one general catch at the very end. So you decide where each catch goes.
1showSpinner();2 3bookSeats(["A1", "A2"])4 .then((id) => console.log("Booked:", id))5 .catch((err) => console.log("Oops:", err.message))6 .finally(() => hideSpinner());And now one more helper, finally. It runs at the end, whether the promise was fulfilled, or rejected. Perfect for cleanup. So here, we show a loading spinner before booking, and hide it in finally. Success or failure, the spinner always goes away. Without finally, you'd have to hide it in two places. So remember, finally is for cleanup.
1new Promise(function (resolve, reject) {2 resolve("first");3 resolve("second");4 reject(new Error("third"));5}).then(function (value) {6 console.log(value);7}).catch(function (err) {8 console.log(err.message);9});What gets printed?
Show the answer
So the first resolve settles the promise, with first. After that, the promise is done. The second resolve is ignored, and so is the reject. So then runs once, and prints first. And catch never runs at all. Just first! So a promise keeps its first word.
Build a chain of four promises yourself. bookSeats, makePayment, sendTicket, and addRewards. Each one returns a promise. Chain them, pass the data down, and handle the errors. Then paste your code in the comments. I'd love to read it.
Show the answer
One way to write it. Each function returns a promise, each then returns the next one, and one catch at the end handles a failure in any step:
1function bookSeats(seats) {2 return new Promise((resolve, reject) => {3 if (seats.length === 0) {4 reject(new Error("Pick at least one seat"));5 return;6 }7 setTimeout(() => resolve({ id: 101, seats: seats }), 500);8 });9}10 11function makePayment(booking) {12 return new Promise((resolve) => {13 setTimeout(() => resolve({ bookingId: booking.id, amount: 300 * booking.seats.length }), 500);14 });15}16 17function sendTicket(payment) {18 return new Promise((resolve) => {19 setTimeout(() => resolve("TKT-" + payment.bookingId), 500);20 });21}22 23function addRewards(ticket) {24 return new Promise((resolve) => {25 setTimeout(() => resolve(ticket + " +50 points"), 500);26 });27}28 29bookSeats(["A1", "A2"])30 .then((booking) => makePayment(booking))31 .then((payment) => sendTicket(payment))32 .then((ticket) => addRewards(ticket))33 .then((result) => console.log("All done!", result))34 .catch((err) => console.log("Failed:", err.message));After about two seconds it prints All done! TKT-101 +50 points. Now call bookSeats([]): bookSeats rejects, every then is skipped, and the catch prints Failed: Pick at least one seat.
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.