In this tutorial, we will discuss Promise chaining in JavaScript. Before turning to Promise chains, let’s first talk about what Promise is
So, we know that JavaScript is single-threaded, which means that two functions are not allowed to run at the same time, because we only have one call stack, as shown below, which has one function to executeWhen one function completes execution, another function starts execution, so in order to achieve two or more functions running at the same time, we use asynchronous programming in the JavaScript example - setTimeout function, which accepts a callback function and the specified time, After that it will execute the function.
setTimeout(function cT(){ console.log("I am here after 5 seconds") }, 5000);Therefore, we use Promise for asynchronous operations, which gives the result of the asynchronous operation and its completion or failure.
Just like in real life, we commit to completing any work in the same way that we make a commitment, and it exists in one of three states.
- Pending - This represents the initial state, meaning it is neither completed nor rejected.
- Fulfilled - This means that the operation we assigned completed successfully.
- Rejected - This status means that the operation cannot be performed and it is rejected.
We use the
then() method to execute the Promise after the Promise statement. If it is rejected due to some error, it will be processed using a catch block.
How to declare Promise in JavaScript?
let promise = new Promise(function (resolve, reject) {
return resolve("Hello I am resolved");
});
There is a function inside the promise here, called the callback function, which has a parameter as two methods resolve() and reject(), as we already know Judging from the above explanations about both.
So resolve here ensures the successful completion of the function we give, while reject will ensure its responsibility for the unsuccessful completion of the given executable callback function.Example 1
Let’s look at a program that uses Set to find unique characters in a string.
<!DOCTYPE html> <html> <head> <title>Promise chaining in JavaScript</title> </head> <body> <h3 id="Execute-a-Promise-we-receive"> Execute a Promise we receive</h3> <p id ="result"></p> <script> let promise = new Promise(function (resolve, reject) { return resolve("Hello I am resolved"); }); promise.then(function(value) { console.log(value); document.getElementById("result").innerHTML += value; }) </script> </body> </html>Inside above. The then() method will pass a callback function, and the value variable is responsible for printing out the results from the resolve() method.
What is a promise chain?
Promise chains are basically multiple asynchronous function calls and executing them one after the other in a synchronous manner. then() method.
Example 2
Let us understand in detail through an example.
<!DOCTYPE html> <html> <head> <title>Promise chaining in JavaScript </title> </head> <body> <h3 id="Promise-Chaining"> Promise Chaining</h3> <p id ="result"></p> <script> let promise = new Promise(function (resolve, reject) { return resolve(10); }); promise.then(function(firstPromise_val) { alert(firstPromise_val) document.getElementById("result").innerHTML += "First Promise val: "+firstPromise_val+"<br>"; return firstPromise_val+10; }). then(function(secondPromise_val){ alert(secondPromise_val) document.getElementById("result").innerHTML +="Second Promise val: "+ secondPromise_val+"<br>"; return secondPromise_val+10; }). then(function(thirdpromise_val){ alert(thirdpromise_val) document.getElementById("result").innerHTML +="Third Promise val: "+thirdpromise_val+"<br>"; return thirdpromise_val+10; }) </script> </body> </html>Let us understand how promise chain works.
- The first initial promise was fulfilled.
- Then the
- .then() method calls it to create a new Promise and get it resolved. Calling the
- .then() method again, it creates a new Promise, which then also gets resolved. Again, it's working, we can also add another promise handler.
.then() method returns a new Promise and uses .then() to call next and so on.
Example 3
<!DOCTYPE html>
<html>
<head>
<title>Promise chaining in javascript</title>
</head>
<body>
<h3 id="Promise-Chaining"> Promise Chaining</h3>
<p id ="result"></p>
<script>
let promise = new Promise(function (resolve, reject) {
return resolve("My");
}).
then(function(firstPromise_val) {
alert(firstPromise_val)
return firstPromise_val+" Name";
}).
then(function(secondPromise_val){
alert(secondPromise_val)
return secondPromise_val+" is";
}).
then(function(thirdpromise_val){
alert(thirdpromise_val)
return thirdpromise_val+" Kalyan";
}).
then(function(thirdpromise_val){
alert(thirdpromise_val)
document.getElementById("result").innerHTML = thirdpromise_val
})
</script>
</body>
</html>
So we see an in-depth concept from the basics to the promise chain on how it works. The above is the detailed content of What is Promise chaining in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.


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

SublimeText3 Chinese version
Chinese version, very easy to use

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

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