Learn javascript promises. Part 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):
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!
The above is the detailed content of Learn javascript promises. Part What is a promise?. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

Learning JavaScript is not difficult, but it is challenging. 1) Understand basic concepts such as variables, data types, functions, etc. 2) Master asynchronous programming and implement it through event loops. 3) Use DOM operations and Promise to handle asynchronous requests. 4) Avoid common mistakes and use debugging techniques. 5) Optimize performance and follow best practices.

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

Explore the implementation of panel drag and drop adjustment function similar to VSCode in the front-end. In front-end development, how to implement VSCode similar to VSCode...
