Understanding Promises in JavaScript might seem complex initially, but in actuality, it is straightforward and not overly complicated. In JavaScript, a promise resembles a real-life commitment made to demonstrate dedication towards completing a task.
Consider a scenario where I commit to achieving high scores in mathematics. This commitment entails two possible outcomes: fulfillment (resolution) or non-fulfillment (rejection). If I succeed in obtaining good grades, the commitment is resolved. Conversely, if I fall short of achieving high marks, the commitment remains unresolved since I did not uphold my commitment.
In JavaScript, a promise can have three possible outcomes: it can be resolved, rejected, or in a pending state. When a promise is pending, it indicates that the promise has not been fulfilled yet and may still be resolved or rejected at a later time.
Let's explore another illustration to grasp the notion of Promise in the JavaScript programming language:
Assume a scenario where a request is initiated to retrieve information from the server through a Promise. If the data is successfully obtained from the server, the Promise is deemed as resolved. However, if the data retrieval fails for any reason, the Promise is considered rejected or unresolved.
Syntax of Promise in JavaScript
Let p= new Promise((resolve,rejected)) =>{
Instructions
}
Now, let's explore the process of creating and utilizing a promise in JavaScript.
Initially, a promise needs to be generated utilizing the constructor function:
constPromise =newPromise
The Promise function is defined with two parameters, as we have previously observed when exploring the syntax of how Promises are constructed.
constPromise =newPromise((resolve, reject)=>{
Condition
});
Here is the final segment known as the condition. If the condition evaluates to true, the Promise will be fulfilled; if not, the Promise will be rejected.
constPromise =newPromise((resolve, reject)=>{
let condition;
if(condition is met){
resolve('Promise is resolved successfully.');
}else{
reject('Promise is rejected');
}
});
So here is our first Promise. Now let's use it.
The then method
As previously mentioned, when it comes to promises, there are two primary scenarios to consider: one for when the promise is fulfilled and another for when it is rejected. Once a promise is fulfilled, subsequent actions will be taken based on how we intend to handle the resolved promise.
myPromise.then();
The ".then;" function is executed solely after the successful resolution of a Promise. Any arguments passed into it will be shown. As an illustration, a message can be provided for the user within this function.
myPromise.then((message)=>{
console.log(message);
});
The .catch; method
This function is invoked when the promise is not fulfilled (or fails). Additionally, it allows us to include a custom message for the user. The catch method can be implemented directly following the "then" method.
myPromise.then((message)=>{
console.log(message);
}).catch((message)=>{
console.log(message);
});
When a Promise is resolved, the message provided in the ".then" method will be displayed on the screen. Conversely, if the Promise is rejected, the message specified in the ".catch" method will be shown. Therefore, distinct messages will appear on the screen depending on whether the Promise is resolved or rejected.
To grasp the concept of promises better, let's delve into the following illustration:
Program
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<script>
const myPromise = new Promise((resolve, reject) => {
let condition=9;
if(condition<0) {
resolve('Promise is resolved successfully and then() method will be called');
} else {
reject('Promise is rejected and catch() method will be called');
}
});
myPromise.then((message) => {
console.log(message);
}).catch((message) => {
console.log(message);
});
</script>
</body>
</html>
Explanation of the program
Within the program mentioned above, a promise has been instantiated through the constructor by providing resolve and reject as arguments. Within the promise declaration, a variable named "condition" has been established with a value of 9. Subsequently, through an if statement, the value of the variable is evaluated. Should the condition be met, the corresponding block of the if statement will be executed, resulting in the promise being resolved (thereby triggering the then method). Conversely, should the condition not be met, the else block will be executed, leading to the promise being rejected (and consequently invoking the catch method).
Output
To view the result on the console, you can press the "F12" key to access the inspect mode within the web browser.