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!

es6 Article's
30 articles in total
Favicon
Next-Generation Buttons: Implementing the Command Pattern through Web Components
Favicon
Hoisting: facing Temporal dead zone
Favicon
Learn javascript promises. Part 1 — What is a promise?
Favicon
Bootcamping 02: Named exports and default exports - does it really matter?
Favicon
Mastering Modern JavaScript: A Deep Dive into ES6 Function Creation and Best Practices
Favicon
Promises: The Ability to Write Asynchronous Code Using Javascript
Favicon
Exploring JavaScript's Modern Primitives: BigInt and Symbol
Favicon
JavaScript ES6 Release Notes: Unleashing the Power of Modern JavaScript
Favicon
WHY YOU SHOULD LEARN ES6
Favicon
Understanding ES6 API's
Favicon
Transpiler vs Polyfills
Favicon
JavaScript Spread Syntax: Expanding Arrays and Objects
Favicon
API Design and Debugging:A Comprehensive Guide for Beginers🚀
Favicon
Understanding the JavaScript Spread Operator (With Examples)
Favicon
A Comprehensive Guide to ES6 and Arrow Functions
Favicon
Controla tus promesa con JavaScript
Favicon
Sets
Favicon
Enhanced Object Literals
Favicon
Iteration Stament i.e for-of loop
Favicon
1.1 Ins & outs of ES6(JavaScript) Import with Realworld Example and Demo Project.
Favicon
Math Namespace & BigInt
Favicon
JavaScript - Destructuring Arrays & Objects [Live Doc]
Favicon
ES2015 (ES6) Tips, Tricks, Best Practices, and Code Snippet Examples for Your Day-to-Day Workflow
Favicon
Objects in JavaScript
Favicon
Intro to DSA & Big O Notation
Favicon
Execution Context & Call Stack
Favicon
Asynchronous programming in Javascript - Callbacks, Promises & Async Await
Favicon
Loops in JavaScript !!📚🔄
Favicon
Array
Favicon
Functions

Featured ones: