Advertisement
The process of executing a sequence of asynchronous tasks one after another using promises is known as Promise chaining. Let's take an example of promise chaining for calculating the final result,
1new Promise(function (resolve, reject) {
2
3setTimeout(() => resolve(1), 1000);
4})
5.then(function (result) {
6 console.log(result); // 1
7 return result * 2;
8})
9.then(function (result) {
10 console.log(result); // 2
11 return result * 3;
12})
13.then(function (result) {
14 console.log(result); // 6
15 return result * 4;
16});In the above handlers, the result is passed to the chain of .then() handlers with the below work flow,
1. The initial promise resolves in 1 second,
2. After that .then handler is called by logging the result(1) and then return a promise with the value of result \* 2.
3. After that the value passed to the next .then handler by logging the result(2) and return a promise with result \* 3.
4. Finally the value passed to the last .then handler by logging the result(6) and return a promise with result \* 4.
Advertisement
JavaScript Coding Exercise 65
Test your knowledge with this interactive coding challenge.
Start CodingAdvertisement