So you’ve spent some time in JS, and you’ve grown past the phase of being in love with callbacks. You now see that while there is a purpose and reason for every coding pattern, most of the time callbacks just create more mess than needed in complex solutions. Hence, you’ve found the joy of promises!
What Is A Promise
In my opinion, the easiest way to describe what a promise is to think of it in a similar fashion as feeding a child dinner. Take a second and breakdown the “stereotypical” child’s dinner. It can be easily split into three stages, one required step and two optional steps after. Now, let’s take a deeper look.
The Main Corse
When making a Promise, there is a set of logic or function that needs to be completed before moving on. That can be defined as the main course. When feeding your child, before moving on you want them to finish this part of their meal first before moving on to 1 of 2 possible outcomes after.
In essence, that is what the function we’re waiting to finish to resolve or reject is setup to do. Once it’s done, if everything goes great we move onto the designated positive route. If not, then we move into our route to handle this negative outcome. Similar to deciding weather or not a child can get desert after dinner only if they eat all their vegetables.
Let’s say when you come back to check on your kid, things didn’t go as you hoped. The required amount of food you asked them to get desert wasn’t met. Oh, no! Now what?
This is where, in Promise terms, where our catch condition comes into play. Here we decide how to handle issues like this. In some cases this could just be providing your kid/users a message informing them things didn’t go as expected and to try again another time. Obviously you can do whatever best suits your situation here, but overall your handling a situation where things didn’t go as you hoped. And that’s the catch.
So you’ve fed your child dinner, and they eat all the required items to earn what they really want. Dessert! And for relation to a Promise, that would be our then chained handler.
At this point in our promise we’ve run our function, everything went as expected, and we are passing the right value to our then method handler. In the end, like a kid wanting desert, this is really what we wanted out of a promise. To call a function, so that hopefully when everything goes right, we get to handle the result in our then case.
Technical topics never have to be difficult. All it takes is a clear head to understand, and relating concepts to life events to further that understanding. Promises are no exceptions. So the next time you’re in an interview, or just writing some code, and Promises come up, no need to fret. Just take a breathe, and think of giving a kid dinner with a conditional option desert if everything goes well.