Introduction
This article will look at how to use the JavaScript promise chaining technique to execute asynchronous processes in a logical order. We will also understand promise.all() method.
Also Read, Javascript hasOwnProperty
Promise
A promise represents an asynchronous operation's future result. Promises are frequently utilized to handle asynchronous processes in JavaScript. The promise allows asynchronous methods to return values the same way that synchronous methods do. Instead of delivering the final value right away, the asynchronous method returns a promise to supply the value in the future.
A Promise is usually in one of the three states:
- Pending: If a promise is neither fulfilled nor rejected, it is said to be pending. It is the initial state.
- Fulfilled: It means that the operation is complete. If it is fulfilled promise.then(f) will call f as quickly as possible.
- Rejected: It means that the operation failed.
We use the new keyword to construct a promise, and we supply a function to the Promise object. An executor is a function that takes two arguments: resolve for success and reject for failure:
|
Promise Chaining
One of the things that makes a promise so great and easy to implement is promise chaining. We can run a series of asynchronous jobs in a chain, with each task starting as soon as the preceding one finishes.
Sometimes we want to run two or more asynchronous operations in a row, with the next operation starting with the output of the last one. Consider the following scenario:
|
Output:
|
The concept is to send the outcome through a chain of .then handlers.
Here's how it goes:
- The initial promise resolves in 3 seconds (*), after which the.then handler (**) is executed, which produces a new promise (resolved with value 20).
- The following handler (***) receives the previous handler's result, processes it (doubles), and passes it on to the next handler.
- And so on.
- We can see the succession of alert calls can, as a result, be transmitted through the chain of handlers: 10→ 20→ 60
The return value from the first then() method is provided to the second then() method, and you can keep calling the then() method over and over again; this mechanism of calling then() methods like this is known as a promise chain.
Multiple handlers for a promise
It's not promise chaining if you call the then() method on a promise several times. We can technically add as many .then as we like to a single promise. This isn't the same as chaining. Consider the following scenario:
|
Output:
|
So the output of the above code shows the same result: 10.
We used multiple handlers to fulfil a single promise. They don't share the result; instead, they process it separately. In practice, numerous handlers for a single promise are rare. Generally, we use chaining.
A promise with several handlers: