Logo

dev-resources.site

for different kinds of informations.

Learn javascript promises. Part 1 — What is a promise?

Published at
1/2/2025
Categories
javascript
es6
programming
basic
Author
volodymyr_potiichuk
Categories
4 categories in total
javascript
open
es6
open
programming
open
basic
open
Author
19 person written this
volodymyr_potiichuk
open
Learn javascript promises. Part 1 — What is a promise?

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):

Actor’s diagram

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:

Promise usage example

Let’s review this code in order:

  1. 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.

Promise states diagram

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.

  1. 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 .then as a handler for both cases (positive and negative)

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:

Using .then for positive and .catch for negative

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:

Using [Promise.prototype.finally](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/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:

Demo of simple promise use

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!

basic Article's
30 articles in total
Favicon
Research DevOps metrics and KPIs
Favicon
Matanuska ADR 010 - Architecture, Revisited
Favicon
Matanuska ADR 009 - Type Awareness in The Compiler and Runtime
Favicon
Matanuska ADR 007 - Type Semantics for Primary Types
Favicon
Top 10 Programming Languages in 2025
Favicon
PHP OOP Part-2: Constructor and Destructor
Favicon
PHP OOP Part-4: Static property, method and this vs self
Favicon
PHP OOP Part-3: Access modifier, Encapsulation and Inheritance
Favicon
PHP OOP Part-5: Abstraction and Interface
Favicon
Matanuska ADR 006 - Runtime Exit
Favicon
Load balancer vs Gateway vs reverse proxy vs forward proxy
Favicon
Sponsoring Family in Dubai: Who Can Apply and How?
Favicon
Best practices to Implement RTL in React Js
Favicon
Matanuska ADR 002 - Architecture
Favicon
Matanuska ADR 003 - Recursive Descent Parser
Favicon
Getting Started with Python: Why and How to Learn This Amazing Language
Favicon
Beginner-Friendly Basic Computer Course Overview
Favicon
I'm Publishing Matanuska BASIC's ADRs
Favicon
Engineering of Small Things #2: Cookies
Favicon
PHP OOP Part-7: Composition vs Inheritance and Dependency Injection
Favicon
A Beginner’s Guide to React: Understanding Components
Favicon
Matanuska ADR 008 - Sigils
Favicon
Correct Way to Implement RTL in React Js
Favicon
Hackathon 101
Favicon
Learn javascript promises. Part 1 — What is a promise?
Favicon
PHP OOP Part-6: Polymorphism
Favicon
PHP OOP Part-1: Introduction, Object, and Class
Favicon
Matanuska ADR 005 - Editor Operations
Favicon
Create Class and Object
Favicon
Java basic program with expansion

Featured ones: