Updated June 26, 2023
Introduction to JavaScript Promise
JavaScript promise is the object that will generate a state with some value in the present or in the future about what is the state of the object with proper reason to the end-user like resolved value or error value.
It has 4 states:
- Fulfilled: Event action about promised success.
- Rejected: Event action about promise failed.
- Pending: Event action about why the promise is still pending.
- Settled: Whether someone fulfills or rejects the promise.
JavaScript promises users can attach a callback for handling the fulfilled, rejected, and pending state to the end-user. JavaScript uses promises for handling asynchronous operations. Promises are very easy to manage while working with multiple asynchronous functionality operations where callbacks create callback-hell leads to unmaintainable application code. You can observe the below image for a clear understanding.
Advantages:
- Better Readability of Application.
- Good for asynchronous.
- Error Handling is easy.
How does Promise Work in JavaScript?
JavaScript promise is working based on “promise constructor”, promise consumers:
Syntax #1
var promiseVariable= new Promise(function(resolve, reject){
//JavaScript logic
});
Explanation: The promise () constructor accepts one argument as a callback function. callback function(function(resolve, reject)) accepted 2 parameters. After calling callback function then, the operation will perform based on the logic written inside the function. If everything is executed fine, the callback function calls the resolved state. The callback function calls the reject state if everything is not executed fine. Promise Consumers: Promise consumers can be registered using then-and-catch functions in JavaScript.
Syntax #2
.then(function(output){
//success message
}, function(errorMessage){
//error resolving logic
})
Explanation: Promise consumers then functions working for displaying the success message of the application. then() function accepts only one callback function with a single parameter. then() function is always followed by another function for displaying the error message of the application.
Syntax #3
.catch(function(errorMessage){
//error resolving logic
})
Explanation: Promise consumer catch function working for displaying the error message of the application. catch() function accepts only one callback function with a single parameter. catch() function is always preceded by the Catch() function to display an error message within the application.
Syntax #4
The Promise() function can also show the error message using the Error() function.
var error=new Promise(function(resolve, reject) {
throw new Error('Error Message')
})
Examples to Implement JavaScript Promise
Below are the examples mentioned:
1. Promise with Equal Variable Comparation
Code: PromiseComparation.html
<!DOCTYPE html>
<html>
<title>Promise in JavaScript</title>
<script>
var promise = new Promise(function(resolve, reject) {
var firstString = "I am Fine";
var secondString= "I am Fine"
if(firstString===secondString) {
resolve();
} else {
reject();
}
});
promise.
then(function () {
document.write('Yeah, I am in Resolve state condition');
}).
catch(function () {
document.write('Opps! I am in Reject state condition');
});
</script>
</html>
Output:
2. Promise with Nonequal Variables Comparation
Code: NonEqualVariable.html
<!DOCTYPE html>
<html>
<title>Promise in JavaScript</title>
<script>
var promise = new Promise(function(resolve, reject) {
var firstString = "I am Fine";
var secondString= "I am Sad"
if(firstString===secondString) {
resolve();
} else {
reject();
}
});
promise.
then(function () {
document.write('Yeah, I am in Resolve state condition');
}).
catch(function () {
document.write('Opps! I am in Reject state condition');
});
</script>
</html>
Output:
3. Promise Consumer for Resolved state
Code: PromiseConsumerResolved.html
<!DOCTYPE html>
<html>
<title>Promise in JavaScript</title>
<script>
var promise = new Promise(function(resolve, reject) {
resolve('I am executing from then function because of successful functionality');
})
promise
.then(function(gainMessage) {
document.write(gainMessage); // resolve() function executes because of calling resolve function
}, function(bugMessage) {
document.write(bugMessage);
})
</script>
</html>
Output:
4. Promise Consumer for Reject state
Code: PromiseConsumerReject.html
<!DOCTYPE html>
<html>
<title>Promise in JavaScript</title>
<body>
<script>
var promise = new Promise(function(resolve, reject) {
reject('I am executing from error function because of calling reject function');
})
promise
.then(function(gainMessage) {
document.write(gainMessage);
}, function(bugMessage) { //error handler function executes because of calling reject function
document.write(bugMessage);
})
</script>
</body>
</html>
Output:
5. Promise Consumer for Error state from catch function
Code: PromiseConsumerRejectWithCatch.html
<!DOCTYPE html>
<html>
<title>Promise in JavaScript</title>
<body>
<script>
var promise = new Promise(function(resolve, reject) {
reject('I am executing from catch function because of calling reject function')
})
promise
.then(function(gainMessage) {
document.write(gainMessage);
})
.catch(function(errMsg) {
//error handler function executes because of calling reject function
document.write(errMsg);
});
</script>
</body>
</html>
Output:
6. Promise Consumer for Error state from Error function
Code: PromiseError.html
<!DOCTYPE html>
<html>
<title>Promise in JavaScript</title>
<head>
</head>
<body>
<script>
var promise = new Promise(function(resolve, reject) {
throw new Error('I am executing from catch function because of calling Error function')
})
promise
.then(function(gainMessage) {
document.write(gainMessage);
})
.catch(function(errMsg) {
//error handler function executes because of calling Error function
document.write(errMsg);
});
</script>
</body>
</html>
Output:
Conclusion
Promise constructor in JavaScript alerts the end-user about application status like fulfilled, rejected, pending, and settled. It mainly works with asynchronous applications.
Recommended Articles
We hope that this EDUCBA information on “JavaScript Promise” was beneficial to you. You can view EDUCBA’s recommended articles for more information.