What is Promise?
The promise is a JavaScript class, objects of which promises eventual completion of some operations. The object of promise can be created as shown below:
let objPromise = new Promise((resolve, reject) => {});
JavaScript promises are not different than the promises we make in real life, either the promise is kept which corresponds to resolve in JavaScript or the promise is not kept which corresponds to reject in JavaScript. A promise object looks like that shown in the below image:
Promise object |
3 important methods that continue the code flow after promise resolve or reject
Below are the three methods that continue the flow or we can call them consumers of the promise object:
- then method - Contains the code block to execute after the promise is resolved
- catch method - Contains the code block to execute after the promise is rejected
- finally method - Contains the code block that needs to be executed irrespective to the promise being resolved or rejected
If we compile everything the promise will look like below image:
Promise with then, catch and finally |
Use Case: If we need any variable for further execution of code
In the below example, I have added timeout of 100ms to call the method add(2, 3). Suppose there is a set of code that needs this answer to carry on further operations, we can do it in then method block as shown below. Here, I have displayed the value.
var add = (var1, var2) => {
return parseInt(var1) + parseInt(var2);
};
let objPromise = new Promise((resolve, reject) => {
var ans;
setTimeout(function() {
ans = add(2, 3);
if (typeof ans != undefined && !isNaN(ans)) {
resolve(ans);
} else {
reject("failed");
}
}, 100);
});
objPromise.then((message) => {
document.write(message);
});
objPromise.catch((message) => {
document.write("Catch block " + message);
});
Try calling add(2, "") and check the output. Here is the JSFiddle link for your reference. I hope, you understood what JavaScript promise is. For any queries, you can write to me at [email protected]. To get notified for the releases, subscribe through email. If you found this article useful, please share it. Thank you 😊.