Promises, Promises 👨‍💻

Okay, I haven’t given up on learning this JavaScript concept, even though it’s taken me literally at least 6 hours (including my tutoring session from Tuesday), and I think I may have cracked the code.

I also think I may have come up with a better analogy than most I’ve seen, for describing the basic premise of a Promise, and how you set it up.

So let’s say there’s a night club that you want to enter. The nightclub owner hires a bouncer at the front door to check that you’re at least 21, and your outfit matches the dress code.

In this scenario:

  • The nightclub owner is the JavaScript developer.
  • Your desire to get inside the nightclub is a callback function that you want to execute.
  • The bouncer is a Promise.
  • The instructions the nightclub owner gives to the bouncer are the conditions under which the Promise either succeeds or fails, and therefore allows you to enter the club / run your callback function.

If the Promise succeeds (i.e. you are over 21 and dressed appropriately), you not only enter the club, but you get a stamp on your hand showing you’re allowed in. That’s the .then() method that provides you data returned by the Promise, which can be used elsewhere in the code.

If the Promise fails (i.e. you are under 21 or you only came dressed in water wings), you are turned away and the bouncer tells you to try again when you’re older. That’s the .catch() method that returns an error message.

One thing my tutor related to me is that learning Promises in the abstract is actually not terribly useful, since they’re primarily used for calling on external resources – like API’s, JSON data, images, etc – asynchronously.

But I’d still rather know how they work, than just copy and paste some code I don’t understand, and letting it go to work for some narrow purpose.

There you have it!