Promises are used to handle asynchronous operations in JavaScript. They are easy to manage when dealing with multiple asynchronous operations where callbacks can create callback hell leading to unmanageable code.
Prior to promises events and callback functions were used but they had limited functionalities and created unmanageable code.
Multiple callback functions would create callback hell that leads to unmanageable code.
Events were not good at handling asynchronous operations.
Promises are the ideal choice for handling asynchronous operations in the simplest manner. They can handle multiple asynchronous operations easily and provide better error handling than callbacks and events.
-
Benefits of Promises
- Improves Code Readability
- Better handling of asynchronous operations
- Better flow of control definition in asynchronous logic
- Better Error Handling
-
A Promise has four states:
- fulfilled: Action related to the promise succeeded
- rejected: Action related to the promise failed
- pending: Promise is still pending i.e not fulfilled or rejected yet
- settled: Promise has fulfilled or rejected
-
A promise can be created using Promise constructor.
Syntax
var promise = new Promise(function(resolve, reject){ //do something });
Parameters
- Promise constructor takes only one argument,a callback function.
- Callback function takes two arguments, resolve and reject
- Perform operations inside the callback function and if everything went well then call resolve.
- If desired operations do not go well then call reject.
Example
var
promise =
new
Promise(
function
(resolve, reject) {
const x =
"geeksforgeeks"
;
const y =
"geeksforgeeks"
if
(x === y) {
resolve();
}
else
{
reject();
}
});
promise.
then(
function
() {
console.log(
'Success, You are a GEEK'
);
}).
catch
(
function
() {
console.log(
'Some error has occured'
);
});
chevron_rightfilter_noneOutput:
Success, You are a GEEK
-
Promise Consumers
Promises can be consumed by registering functions using .then and .catch methods.
-
then()
then() is invoked when a promise is either resolved or rejected.
Parameters:
then() method takes two functions as parameters.
- First function is executed if promise is resolved and a result is received.
- Second function is executed if promise is rejected and an error is received. (It is optional and there is a better way to hanlde error using .catch() method
Syntax:
.then(function(result){ //handle success }, function(error){ //handle error })
Example: Promise Resolved
var
promise =
new
Promise(
function
(resolve, reject) {
resolve(
'Geeks For Geeks'
);
})
promise
.then(
function
(successMessage) {
//success handler function is invoked
console.log(successMessage);
},
function
(errorMessage) {
console.log(errorMessage);
})
chevron_rightfilter_noneOutput:
Geeks For Geeks
Examples: Promise Rejected
var
promise =
new
Promise(
function
(resolve, reject) {
reject(
'Promise Rejected'
)
})
promise
.then(
function
(successMessage) {
console.log(successMessage);
},
function
(errorMessage) {
//error handler function is invoked
console.log(errorMessage);
})
chevron_rightfilter_noneOutput:
Promise Rejected
-
catch()
catch() is invoked when a promise is either rejected or some error has occured in execution.
Parameters:
catch() method takes one function as parameter.- Function to handle errors or promise rejections.(.catch() method internally calls .then(null, errorHandler), i.e. .catch() is just a shorthand for .then(null, errorHandler) )
Syntax:
.catch(function(error){ //handle error })
Examples: Promise Rejected
var
promise =
new
Promise(
function
(resolve, reject) {
reject(
'Promise Rejected'
)
})
promise
.then(
function
(successMessage) {
console.log(successMessage);
})
.
catch
(
function
(errorMessage) {
//error handler function is invoked
console.log(errorMessage);
});
chevron_rightfilter_noneOutput:
Promise Rejected
Examples: Promise Rejected
var
promise =
new
Promise(
function
(resolve, reject) {
throw
new
Error(
'Some error has occured'
)
})
promise
.then(
function
(successMessage) {
console.log(successMessage);
})
.
catch
(
function
(errorMessage) {
//error handler function is invoked
console.log(errorMessage);
});
chevron_rightfilter_noneOutput:
Error: Some error has occured
-
then()
-
Applications
- Promises are used for asynchronous handling of events.
- Promises are used to handle asynchronous http requests.
Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise