We all know that javascript is a synchronous programming language but callback functions help to make it an asynchronous programming language.
By the Definition of Javascript, MDN Promises is,
The Promise the object represents the eventual completion (or failure) of an asynchronous operation and its resulting value.
Basically, promises are the same as real-life promises which we are making in real life.
Take an example, suppose you make a promise to your friends that are next weekend you will take them to a party.
But actually, you don’t know you will get time on the weekend or not, means either you are going to complete that promise or maybe not.
So there may be below chances-
Pending: You don’t know you will get time or not
Fulfilled: You gave them a party
Rejected: You don’t give a party to them
So promise start with the pending state then after fulfilled and at the end it in the Rejected state.
There are 2 parts:
new Promise( //* executor*// function(resolve, reject) { ... } );
2.Handling Promises:
let partyPromise = true;
let giveParty = new Promise(function (resolve, reject) {
setTimeout(() => {
if (partyPromise) {
resolve(“I given party to friends”);
} else {
reject(“I am not given party to friends”);
}
}, 5 * 1000);
});
After execution of the above code below, you can see in the below snap there is the first state is pending state
Now after completion of 5 Seconds, it returns the below result that is a fulfilled state.
and after a changed of partypromise = true
to false
, it returns the below result
So the reject method moved the promises to the rejected() state.
The Promise the object represents the eventual completion (or failure) of an asynchronous operation and its resulting value.
promise object having static methods and prototype methods,
The then()
the method is used to schedule a callback to be executed when the promise is successfully resolved.
2. Promise.prototype.catch(onRejected):
If you want to schedule a callback to be executed when the promise is rejected.
3.Promise.prototype.finally(onFinally):
It is used to execute the same piece of code whether the promise is fulfilled or rejected.
See below example :
function makePromise(partyPromise) {
return new Promise(function (resolve, reject) {
setTimeout(() => {
if (partyPromise) {
resolve("I given party to friends");
} else {
reject("I am not given party to friends");
}
}, 5 * 1000);
});
}
let partyPromise = makePromise(true);
partyPromise
.then(success => console.log(success))
.catch(reason => console.log(reason))
.finally(() => console.log("Friends are ready for party !"));
#javascript #web-development #programming #developer