A promise object represents the eventual completion or failure of an asynchronous operation and its resulting value.
in simple words, A Promise has two results:
Fulfilled
Rejected
Let us relate to it with a real-life example. Every year a Promise is made by the Royal Challengers Bangalore that they are going to win the trophy.
If they actually win the trophy, then the promise has been fulfilled
If they don't, then the promise is rejected.
The Promise is one of the most preferred ways of dealing with asynchronous operations in JS.
3 stages in a Promise
Pending: It means the Promise is not yet fulfilled. It's not rejected either.
Resolved: It means the Promise has been fulfilled or successful.
Rejected: It means the Promise has been rejected or failed.
How Promise is different from Callback functions?
In callback functions, we call the callback functions, whereas in Promises we attach a callback function to the Promises.
The main drawback of using callback functions is that when there number of callback functions it leads to Callback Hell (also called "Pyramid of Doom") and we cannot be sure whether all the functions are being executed.
How to Create a Promise?
- Create a Promise Object
const promiseExample = new Promise();
- It has two parameters: resolve and reject.
const promiseExample = new Promise(resolve, reject) => {
//conditions
};
- Write the conditions and then resolve or reject.
const promiseExample = new Promise((resolve, reject) => {
let champions = "RCB";
if(champions == "RCB"){
resolve("this is for our loyal fans");
}
else{
reject("we will come back stronger");
}
});
Promise Chaining
.then()
Once we have declared a Promise, we can use .then() method to handle multiple asynchronous operations.
Let us look at an example
const promiseEx = new Promise((resolve, reject) => {
const randomNumber = Math.random();
if (randomNumber < 0.5) {
resolve(randomNumber);
} else {
reject("The number is greater than or equal to 0.5");
}
});
promiseEx
.then(result => {
console.log("Resolved:", result);
});
In the above code, a promise called PromiseEx is created to generate a random number and store it in the const randomNumber.
If the randomNumber is less than 0.5, the Promise is resolved, else it is rejected.
We have attached the .then() method to promiseEx to handle the resolved value and then it is logged.
.catch()
.catch() method is used for effective Error Handling in the Promises. It is used to handle the rejected Promises
Let us see an example:
const promiseEx = new Promise((resolve, reject) => {
const randomNumber = Math.random();
if (randomNumber < 0.5) {
resolve(randomNumber);
} else {
reject("The number is greater than or equal to 0.5");
}
});
promiseEx
.then(result => {
console.log("Resolved:", result);
});
.catch( error => {
console.log("Rejected:" , error);
});
I hope this article helped you in understanding the basics of Promise in JavaScript. Thank You.