Promise Chaining is a simple concept that enables us to create a subsequent promise within the .then method and subsequently process our outcomes based on that. The result produced by the prior promise is then taken up by the function located within.
There are situations where it becomes necessary to execute multiple interconnected asynchronous tasks, where the initiation of the subsequent task depends on the result of the preceding one.
Promises are particularly useful when it comes to coordinating several asynchronous operations in a sequential manner. To achieve this, we utilize promise chaining. By leveraging the methods then, catch, and finally, we can execute a specific action after a promise has been resolved.
Syntaxes for promises in a chain
First syntax
At times, there is a need to execute multiple asynchronous operations sequentially. Additionally, it is essential to pass the results from one phase to the next. In this scenario, we can utilize the following syntax:
Promise_step1()
.then(result => Promise_step2(result))
.then(result => Promise_step3(result))
...
.then(result => Promise_stepN(result))
Second syntax
Utilize the following syntax when it is necessary to relay the outcome from the preceding task to the following one without directly transferring the result:
Promise_step1()
.then(Promise_step2)
.then(Promise_step3)
...
.then(Promise_stepN)
How to operate promise chaning
The syntax illustrates the operation of promise chaining in JavaScript, along with its functional process.
<script>
let promise_variable = new Promise((resolve, reject) => {
resolve("JavaScript chaining");
});
promise_variable
.then( function (resultInfo1){
console.log(resultInfo1);
return new Promise((resolve,reject) =>{
resolve("Example");
})
})
.then((resultInfo2) => {
console.log(resultInfo2);
});
</script>
Explanation
- The promise function uses with the then method.
- The method shows the console tab to get the output.
- The second promise function places inside of the first then function.
- We can resolve and reject operations to get the output data and functionality.
Examples
The subsequent examples illustrate the process of chaining with the promise function. In the example provided, multiple handlers are bypassed by utilizing promise chaining.
Example 1
The fundamental promise chaining function illustrates the output of two promise values. In this scenario, we utilize three promises along with the then method.
<!DOCTYPE html>
<html>
<head>
<title> JavaScript's Promise.allSettled() method </title>
<script>
console.log("JavaScript's Promise Chaining Function");
let promise_variable = new Promise((resolve, reject) => {
resolve("JavaScript chaining");
});
promise_variable
.then( function (resultInfo1){
console.log(resultInfo1);
return new Promise((resolve,reject) =>{
resolve("Example");
})
})
.then((resultInfo2) => {
console.log(resultInfo2);
return new Promise((resolve,reject) =>{
resolve("TutorialsAndExamples");
})
})
.then((resultInfo3) => {
console.log(resultInfo3);
});
</script>
</head>
<body>
<h3> JavaScript's Promise Chaining Function </h3>
<p> The output information shows in the console tab </p>
</body>
</html>
Output
The image shown illustrates the results produced by promise chaining functions.
Example 2
The JavaScript promise chaining function demonstrates the outcome of multiple promise values through a series of operations. We utilize different promises along with the then method, specifying the necessary timing for each operation.
<!DOCTYPE html>
<html>
<head>
<title> JavaScript's Promise Chaining Function </title>
<script>
console.log("JavaScript's Promise Chaining Function");
let promise_var = new Promise((resolve, reject) => {
setTimeout(() => {
resolve(18);
}, 3 * 10);
});
promise_var.then((result_var) => {
console.log(result_var);
return result_var * 2;
}).then((result_var) => {
console.log(result_var);
return result_var * 3;
}).then((result_var) => {
console.log(result_var);
return result_var * 4;
}).then((result_var) => {
console.log(result_var);
return result_var * 5;
}).then((result_var) => {
console.log(result_var);
return result_var * 5;
});
</script>
</head>
<body>
<h3> JavaScript's Promise Chaining Function </h3>
<p> The output information shows in the console tab </p>
</body>
</html>
Output
The image shown illustrates the output generated by promise chaining functions.
Example 3
The JavaScript promise chaining functionality demonstrates the output of multiple promise values alongside their corresponding operations. It employs several promises in conjunction with the then method, each executed in the specified time frame.
<!DOCTYPE html>
<html>
<head>
<title> JavaScript's Promise Chaining Function </title>
<script>
console.log("JavaScript's Promise Chaining Function");
let promise_var = new Promise((resolve, reject) => {
setTimeout(() => {
resolve(18);
}, 3 * 10);
});
function getEmployee(empId) {
return new Promise((resolve, reject) => {
console.log('Get the user from the database.');
setTimeout(() => {
resolve({
empId: empId,
empname: 'admin'
});
}, 100);
})
}
function getWorkData(emp) {
return new Promise((resolve, reject) => {
console.log(`Get the employee data of ${emp.empname} from the API.`);
setTimeout(() => {
resolve(['Email', 'NUMBER', 'VPN']);
}, 3 * 100);
});
}
function getWorkDataCost(services) {
return new Promise((resolve, reject) => {
console.log(`Calculate the Employee working cost of ${services}.`);
setTimeout(() => {
resolve(services.length * 100);
}, 2 * 100);
});
}
getEmployee(10)
.then(getWorkData)
.then(getWorkDataCost)
.then(console.log);
</script>
</head>
<body>
<h3> JavaScript's Promise Chaining Function </h3>
<p> The output information shows in the console tab </p>
</body>
</html>
Output
The image presented illustrates the output of functions that utilize promise chaining.
Multiple handlers for promise chaning
The promise chaining mechanism does not function as expected when the then method is invoked multiple times on a single promise. A single promise can have multiple handlers associated with it. However, these handlers operate independently from one another, lacking any direct linkage. Additionally, in contrast to the promise chain, these handlers execute in isolation and do not transfer output from one to the next.
Example
The subsequent illustration demonstrates the utilization of one promise to accommodate several handlers. The results reveal the starting promise value for every handler involved.
<!DOCTYPE html>
<html>
<head>
<title> JavaScript's Promise Chaining Function </title>
<script>
console.log("JavaScript's Promise Chaining Function");
let promise_var = new Promise((resolve, reject) => {
setTimeout(() => {
resolve(15);
}, 3 * 10);
});
promise_var.then((result_var) => {
console.log("first promise value:"+result_var);
return result_var * 2;
})
promise_var.then((result_var) => {
console.log("second promise value:"+result_var);
return result_var * 3;
})
promise_var.then((result_var) => {
console.log("Third promise value:"+result_var);
return result_var * 4;
})
</script>
</head>
<body>
<h3> JavaScript's Promise Chaining Function </h3>
<p> The output information shows in the console tab </p>
</body>
</html>
Output
The image presented illustrates the output generated by promise chaining functions.
Conclusion
Promise chaining demonstrates various outputs by utilizing the "then" method. This method operates on the promise variable. It is effective for both singular inputs and numerous outputs derived from calculations.