Learn javascript promises. Part 1 — What is a promise?
Hey, javascript fans, today I will tell you about promises and how you can learn or understand them better. Many people think that this is a complicated topic and get confused about it, although there is nothing tricky about it, and if you practice it often, you’ll become an expert, I guarantee it. My task today is to help you understand the basics, and to demonstrate the essence of promises and why we need them.
What is a promise and why do you need it in javascript?
Imagine you have pledged to your friends that you will continuously exercise each morning and notify them if you do that. Your promise is not blocking you or your friends from doing their life and they are just waiting for your notification about the pledge’s success or failure to make their conclusions or actions about you.
This small example illustrates the nature of the promise as an event and the two actors that are connected by this event: in this case, it’s the consumer (your friends), and the producer (you):
And if we simplify it a bit, we can say that in javascript we see the same behavior with the Promise class, which gives us the ability to perform asynchronous tasks without blocking the main thread of the javascript and notify subscribers when we finish our promise.
Let’s take an example to figure out how to work with it:
Let’s review this code in order:
- We create a promise instance with an executor function (it’s a function that we pass to the Promise class constructor).
The executor function is the basis of the promise, and this function is called instantly when the promise is created.
The executor function takes two positional parameters, the first is the resolve method and the second is the reject method. Both of these methods are responsible for finishing promise in some time.
For example, we promised to get up every morning and exercise for a week. In this case, our promise lasts for a whole week, and if you can’t keep it on day 3, you can call the reject method and everyone who is subscribed to your promise will know about it. Or vice versa, if you keep your promise, then on day 7 you will call the resolve method, which will inform your friends that you have successfully kept your pledge. So you can see that the consumers (your friends) are completely independent of when you tell them the results, they just need to be sure that when they are, they will be able to get them.
The picture below shows the possible promise states, they are “pending”, “fulfilled” and “rejected”. When a promise is just initiated, its status is “pending”. After it is completed, it is either “fulfilled” or “rejected”, depending on which method was called to complete it.
It is also worth noting that a promise executor cannot be completed more than once, all subsequent calls to resolve or reject methods will be ignored.
- At the moment when you say you finished your promise (by calling the resolve or reject) method, all those who have subscribed to the promise will receive a notification with payload, which can be retrieved inside two special methods of the promise instance. Those methods are: Promise.prototype.then and Promise.prototype.catch
Using the Promise.prototype.then method, you can handle both positive and negative scenarios at once, as the function accepts two callbacks as in the screenshot above.
With Promise.prototype.catch you can handle only negative scenarios like this:
and leave the Promise.prototype.then for positive scenarios.
Also, promises provide a method that you can use to execute code that should be executed regardless of the result. This method is Promise.prototype.finally:
This method takes nothing and returns nothing, as it is designed to complete or clean up previous operations. For example, to show the message to the user or to hide the loader.
Great, at this point, we’ve covered the basics of promises, so I suggest we move on to a real-world example, like requesting data from the API, transforming it from raw HTTP response to JSON, and outputting it to the console:
As you can see, the result of using it in the real world is not much different from the skills we practiced at the beginning of the article. But still, you may have noticed a couple of new things:
The result from each previous Promise.prototype.then and Promise.prototype.catch handlers are passed to the next Promise handler. It’s good to mention that the Response.json method returns a promise, which in turn, when executed, will return a JSON, and will call the following handler passing that JSON to it.
In the case of Promise.prototype.finally, it is an “invisible” handler, and you can say that it passes the previous response through itself into the next one.
Awesome, I’m sure at this point you have a better understanding of what a promise is, how to use it, and what states it can have. Also, I want to list below the key points that we went over today (cheatsheet):
Summary:
Javascript promise — it is a special object that allows you to execute asynchronous operations and notify consumers of it when it’s done
Promise instance can have 3 states —”pending”, “fulfilled” and “rejected”
There are three main methods of the promise instance — “then”, “catch” and “finally”.
Promise.prototype.then — designed to handle both rejections and successful results
Promise.prototype.catch — designed to handle rejected results
Promise.prototype.finally — designed to make some cleanup work
You can chain your handlers in any order that you want, they will be executed sequentially
The result from the previous promise goes into the next, so to make the promise chain extensible, you must remember to return a promise from handlers every time except for the “finally” handler.
In future parts of this topic, we’ll cover more advanced promise techniques and delve deeper into its capabilities, so subscribe, like, and stay tuned!
Top comments (0)