Promise in JavaScript
A promise in JavaScript works as same as a promise in a real-life, where a promise is either fulfilled(resolved) or incomplete(rejected). Since javascript is a single-threaded synchronous language the use of promise makes it perform an a-synchronous task also because of which it makes javascript one of the most powerful programming languages. There are two methods of using promises i.e .then().catch() method and the async-await method but in the async-await method, we use try to get the resolved result from the promise and catch to get the rejected results i.e if there are any error or failure while getting the result it will be caught in the catch.
E.g.:
let p = new Promise((resolve,reject) => {
let a = 1 + 1;
if(a == 2) {
resolve('Success');
} else {
reject('Failed');
}
});
p.then((message) => {
console.log('This is in then' + message);
})
.catch((message) => {
console.log('This is in catch' + message);
})
In the above, our promise will always be successful because a = 1 + 1;
which is equal to 2 and the condition we are considering here is a == 2
so our promise will always be resolved unless we do not alter the value of a.
i.e.: If we change a to a = 1 + 2;
then a will not be equal to 2 hence the promise will fail and will be rejected.
To interact with the promise we use .then()
when the promise is a success and .then()
will use a callback function in our case the callback function is:
(message) => {
console.log('This is in then' + message);
}
Which will return an output of:
This is in then success
And we use .catch()
to catch the errors if the promise fails. Similar to .then()
, .catch()
will also use a callback function in our case the callback function is:
(message) => {
console.log('This is in catch' + message);
}
Which will return an output of:
This is in then failed
.