The Promise object represents the eventual completion/failure of an Asynchronous Operation and its resulting Value.
let promise = new Promise((resolve, reject) => {
// Asynchronous operation.
});
The resolve
function is used to change the state of the Promise from "pending" to "fulfilled" and to set the resulting value of the Promise. The reject
function is used to change the state of the Promise from "pending" to "rejected" and to set the reason for the rejection.
let firstRank=true;
const promiseToParent=new Promise((fulfil,reject)=>{
if(firstRank){
fulfil("I will give you a car");
}else{
reject("I will give you noting");
}
});
console.log(promiseToParent);
then
is called if the Promise is fulfilled (i.e., firstRank
is true).
catch
is called if the Promise is rejected (i.e., firstRank
is false)
promiseToParent.then((data)=>{
console.log(data);
}).catch((error)=>{
console.log(error);
});
then
, catch
statements gets execute only after the promise is either fulfilled or rejected, until then the other statements will be executed due to asynchronous nature of the Promise
Object.
Whenever the client-side app wants to communicate with external application, then we use promises and requests.