Let’s Talk Promises

If you use Node on a regular basis; the chances are you’ve heard of Promises. There are plenty of resources online that explain them, so you might be wondering why I’m writing another one.

Every developer has a topic that, when learning, was their sticking point; the one that no matter how many times someone explained it just didn’t make sense. Promises were mine.

I finally got my head around them, and we’ve been in a loving relationship for years now.

Last week I released my first Medium article; and received some positive feedback, which is why I’m writing another about a topic I really struggled with.

What this tutorial is not.

I am not going to be talking about the Node.js event loop, web API, or callstack. This is not a tutorial on WHY promises work, or HOW they work, it’s just a simple explanation of WHAT they are.

The analogy

Every article I’ve ever read about promises has a good analogy to start with. Keeping with the same tradition, I’m going to do the same.

You are at home, cooking a Roast dinner (I don’t know much about cooking at all, so don’t fact check this bit of the article). You have everything laid out ready to prepare (roast potatoes, parsnips, stuffing) and then you realise… you forgot to pick up the chicken!

Luckily; your partner is sitting on the sofa, not doing very much, so you send them off to the supermarket to pick up a chicken for you.

What has this got to do with Promises? This analogy is going to help me explain the difference between a synchronous and a asynchronous operation.

Let’s start with the synchronous version of this example…

What is a synchronous operation?

Before we talk about synchronous and asynchronous definitions, let’s first take a quick detour into what happens at programme execution. Node will run your application, starting at the first line and running each line of code sequentially thereafter.

A synchronous operation is one that, when your application is being executed line by line, waits for each operation to complete before moving on.