What is a Promise?
A Promise is an object that signifies a value that might not currently be accessible but will be in the future. ‘Promises’ have three states:
- Pending: The initial state of a Promise before it is resolved or rejected.
- Fulfilled: A ‘Promise’ status after it has been fulfilled.
- Rejected: A ‘Promise’ when rejected with an error.
With the help of the Promise Constructor, you can generate ‘Promises.’ The resolve and reject functions are the only two arguments accepted by the Promise function, which only accepts one argument. Here’s an illustration:
Once you have a Promise, you can handle the fulfilled state using the then method and the rejected form using the catch method. Here’s an illustration:
What is Promise Chaining?
When utilizing Promises in a chain, each action is completed in order, and results are supplied as input to the subsequent action. The final operation’s result is returned as the chain’s overall result.
Promise chaining enables you to develop code that is clearer and easier to read by doing away with the requirement for nested callbacks.
Return a new Promise from the then method to link Promises together. The outcome of the previous operation may be used to resolve this new Promise, or it may be refused due to an error.
Below is an illustration of a Promise Chain:
In this instance, the Promise returned by the login user function resolves to a userId, and a new Promise is fixed with a user object. A new Promise that resolves with the user’s details is returned by the first-then method after receiving the userId. The second method uses the userId as a starting point for some processing.
The catch method is called if any of the Promises in the chain are rejected. This enables you to deal with any chain-related errors.
As many Promises as you need to can be linked together. A longer Promise chain looks like this:
In the illustration above, the Promise returned by the getUserFriends function resolves to an array of friend objects. The third then function uses a variety of friends to fetch each friend’s posts by using the Promise—all methods to execute a series of Promises.
View our LinkedIn, here.