Hello friends, we will try to learn the aspect of the promises in javascript how the promises work in the javascript. We will also learn how to use the promises effectively in the Javascript.
1. Definition of the promises in the Javascript
If we will try to understand promises in ordinary language. It will be like if I promise you to do one job for you, the next job will start when the first job completes. Take an example if we have messed our study room. Mother will come and say, please clean the room. If you clean the room, I will give you donuts. Mother has promised the children. If you compete with this task, I will provide you with the donuts. If you don’t, no donuts for you. Similarly, in the javascript, Promise means if you completed a task successfully will resolve; otherwise, it will reject the job.
In Javascript, promises is a way to handle asynchronous operation. We will Understand this article better if we know callbacks in the javascript. We can say that promises have two possible outcomes. It will complete (resolve), or it will fail to do the desire operation(reject). There are three states in the Promise
- Pending : It is the initial state in that it has not been completed or rejected.
- Resolve : Process is completed.
- Reject : Process is not completed.
Let see small example of the Promise in the javascript:
const myPromise = new Promise((resolve, reject) => {
let condition;
if(condition is met) {
resolve('Promise completed');
} else {
reject('Promise rejected');
}
});
To create the Promise in JavaScript, we use the Promise constructor. The Promise we have created accepts a function as an argument. That function is called an executor. That executor has two features they are known as to resolve() and reject(). When we have called the Promise, the executor will automatically call based on the output if successful that resolve() otherwise reject().
If we want to see the Promise’s pending state, we can create a promise that will execute after specified seconds. Let’s take an example. If we want to see the Promise’s pending state, we can create a promise that will execute after specified seconds. Let’s take an example. In this, we have implemented a Promise after five seconds till the Five seconds will complete. The Promise will be in Pending state.
let promiseCompleted = true;
let learnPromise = new Promise(function (resolve, reject) {
setTimeout(() => {
if (promiseCompleted) {
resolve("The promise will complete after 5 seconds.");
} else {
reject("It will be rejected if we will mark completed as reject.");
}
}, 5 * 1000);
});
The pending state will look the image given below. We can see that the state is pending state.
After five seconds, the Promise will complete according to the input parameter we have passed. In this case, the Promise will complete. It will look like this
Promise {<fulfilled>: "The promise will complete after 5 seconds."}
__proto__: Promise
[[PromiseStatus]]: "fulfilled"
[[PromiseValue]]: "The promise will complete after 5 seconds."
In case of rejection, it will look like this, PromiseStatus will reject in this case.
Promise {<rejected>: "It will be rejected if we will mark completed as reject."}
__proto__: Promise
[[PromiseStatus]]: "rejected"
[[PromiseValue]]: "It will be rejected if we will mark completed as reject."
Once the promise reaches it, it will fulfill or reject the state, but it cannot be switchback. Once a new Promise object is created, the promise is pending until it is resolved or rejected.
2. Promises chaining
We have a sequence of the task to be performed asynchronously. Means one after another task takes an example; we are saving a piece of user information first to upload his/her image. After that, we will want another job for this situation we can use Promise chaining. Let’s take an example; we will first fetch authenticate the user. After authentication, we want to check the user is admin or not.
new Promise(function(resolve, reject) {
setTimeout(() => resolve(1), 1000); // (*)
}).then(function(userInfo) {
return userInfo;
}).then(function(isAuthenticated) { // (***)
return isAuthenticated;
}).then(function(userType) {
return userType;
});
3. Using A Promise Step by Step
- In first phase we will call constructor to create Promise Object
const lazyLoad = new Promise();
- It takes two parameters, one for success (resolve) and one for fail (reject):
Finally, there will be a condition. If the user condition is fulfilled, the Promise will resolve. Otherwise, it will reject.
let condition = true;
const lazyLoad = new Promise((resolve, reject) => {
let condition;
if(condition) {
resolve('Promise is resolved successfully.');
} else {
reject('Promise is rejected');
}
});
Finally, we have created the first promise successfully step by step. Lets use it.
4.then( ) for resolved Promises
As we have discussed in the post, there are two conditions Promise will be resolved or get rejected. If the Promise is get resolved we will use then() keyword. We can use then keyword like this
lazyLoad.then((result) => {
console.log(result);
});
If our Promise got rejected(Fail), it will go into the catch method. If our condition get fail in that case, Promise will be rejected. Let’s see the example of the catch in the Promise.
lazyLoad.then((resolveMessage) => {
console.log(resolveMessage);
}).catch((rejectMessage) => {
console.log(rejectMessage);
});
So, if our condition got to fail, it will go to the Promise catch method.
5. finally() Method in the Promises
The finally() method returns a Promise. When the Promise is resolved or rejected based on the condition, we have provided while executing the Promises. finally() offer us a way to implement the code that is common for both resolve() or reject() method. So, finally() method can be used when we want to do some processing or clean the variable after the execution. In that case, we can use finally() method. Let’s take an example.
let condition = true;
const lazyLoad = new Promise((resolve, reject) => {
let condition;
if(condition) {
resolve('Promise is resolved successfully.');
} else {
reject('Promise is rejected');
}
});
lazyLoad.then((resolveMessage) => {
console.log(resolveMessage);
}).catch((rejectMessage) => {
console.log(rejectMessage);
}).finally((message) => {
condition = false;
});
6. Summary
- A Promise is an object in which return value in the future depends upon the user input.
- A Promise always starts in the pending state.
- A Promise always will be resolve or in rejected mode.
- Use then() method while resolving the method.
- Use catch() method while rejecting the method.
- We can use multiple Promises for executing asynchronous calls(Promises chaining).
- Place the common in the finally() method to execute in both of the situations resolve or reject.
Thanks for the article.Its clear mine many doubts
Thanks for the feedback.