JavaScript Promise 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 (a chain of limitless callbacks inside each other) that leads to unmanageable code.
Promises are used to handle asynchronous operations in JavaScript.
Promises are objects that have four states :
1) Pending: The initial state which means not rejected nor resolved.
2) Fulfilled: This term refers to successful completion.
3) Rejected: means the promise cannot be fulfilled due to an error or some exceptional situations in asynchronous operations.
4) Settled: Promise has been fulfilled or rejected
You can decide what to do upon this promise either in the happy way or the errors way, so there are 2 methods to do so
then() and catch()
let promise = new Promise(function (resolve, reject) {
const x = "test";
const y = "test"
if (x === y) {
resolve();
} else {
reject();
}
});
promise
.then(function () {
console.log('Success');
})
.catch(function () {
console.log('Some error has occurred');
});
then() method can take 2nd argument, so you ignore catch()
The second argument is executed if the promise is rejected and an error is received. (It is optional and there is a better way to handle error using .catch() method
let promise = new Promise(function (resolve, reject) {
resolve('test again');
})
promise
.then(function (successMessage) {
//success handler function is invoked
console.log(successMessage);
}, function (errorMessage) {
console.log(errorMessage);
});
Top comments (0)