I promise this will be quick

Jure Stepisnik
tretton37
Published in
2 min readJan 21, 2021

A short story about Javascript promises

Come here let me show you something.

A few moons ago I was reading through the forth book of the You Don’t Know JS series and got really into the chapter about promises. I still remember the first time I saw a promise and how I couldn’t comprehend how it was all working. My first mentor was showing me how to wait for a result of an API request with promises. Seeing the “then” for the first time and later how you can chain multiple “then” calls one after another was mind-blowing.

Now enough about me let’s have a quick history lesson on promises and how we got to where we are now. Promises were not always around despite being the de facto way of handling asynchronous operations. The way we handled asynchronous code in the before time was with callbacks. And oh boy have we all heard or seen the horror stories of callback hell and what not. But what was an even greater reason for the addition of this feature… This was about control.

The issue was that you had to give the control away to another party. So if this third party made a mistake and called the callback multiple times it really messed up your logic. There were some early libraries that battled with this in a similar way that promises later did.

So how do they do it? How do we get back something which is ours? Promises are similar to a placeholder where we know we will get something back one way or another (let it be a resolved or rejected value). This placeholder is there for us as a guarantee, that we are waiting for something. Once it is resolved it cannot be undone or mutated. In other words it is here to stay… Forever. This behaviour is very valuable to us as it means that once we get something nothing can change it.

Another thing promises do very well is that they do it only once. As mentioned before they are immutable. So the issue when a callback could have been called multiple times is resolved (pun intended). This gives us security and trust that it will be triggered only once and not break our code.

I encourage each and everyone to look, learn and learn to love promises. Now back to the title, this was quick wasn’t it?

--

--