The Promise object represents the eventual completion/failure of an Asynchronous Operation and its resulting Value.

Untitled

States of a Promise:

  1. Pending: The Promise's outcome hasn't yet been determined, because the asynchronous operation that will produce its result hasn't completed yet.
  2. Fulfilled: The asynchronous operation has completed, and the Promise's result is a value.
  3. Rejected: The asynchronous operation failed, and the Promise's result is an error.
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.

A simple Promise to Parent

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);

Consuming the promise

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.

Untitled