Promises And Its Types

Promises And Its Types

Promises:

A JavaScript Promise object contains both the producing code and calls to the consuming code. The promise object represents the eventual completion (or failure) of an asynchronous operation and its resulting value.

const myPromise = new Promise((resolve,reject)=>{   //Promise constructor used to wrap function
setTimeout(()=>{
resolve('Promise Successfully')   //This function take 2sec for execution
},2000)
}).then(result=>console.log(result))  //If function is resolve then print 'Hello I Am Promise' 
.catch(err=>console.log(err));  //If Function is reject then throw an error.

[OR]

fetch('https://example-api')
  .then(response => response.json())  //For handeling api data in json format because api data return promise
  .then(data => console.log(data)) //handel response data because response also return promise
  .catch(error => console.error(error))  //handel error if server has any error during api call

Note:- .then() and .catch(), that allow you to handle the resolved value or any errors that may occur during the asynchronous operation.

Promise has 3 states :

  • Pending: initial state, neither fulfilled nor rejected.

  • Resolve: meaning that the operation was completed successfully.

  • Reject: meaning that the operation failed.

  1. Types of Promises:

    There are 4 types of promises:

  • Promise.all: That takes an iterable (such as an array) of promises as input, and returns a new promise that resolves when all of the input promises have resolved, or rejects with the reason of the first promise that rejects.

      const promise1 = Promise.resolve('Hello');
      const promise2 = Promise.resolve('world');
      const promise3 = new Promise((resolve, reject) => {
        setTimeout(() => resolve('from a Promise!'), 2000);
      });
    
      Promise.all([promise1, promise2, promise3])
        .then(values => {
          console.log(values); // Output: ['Hello', 'world', 'from a Promise!']
        })
        .catch(error => {
          console.error(error);
        });
    
  • Promise.allSettled: That returns a promise that resolves after all of the input promises have either fulfilled or rejected, with an array of objects describing the outcome of each promise.

      const promises = [
        Promise.resolve(1),
        Promise.reject('error'),
        Promise.resolve(2)
      ];
    
      Promise.allSettled(promises)
        .then(results => {
          console.log(results);
        });
    
      // Output: 
      // [
      //   {status: "fulfilled", value: 1},
      //   {status: "rejected", reason: "error"},
      //   {status: "fulfilled", value: 2}
      // ]
    
  • Promise.race: That accepts an array of Promises and returns a new Promise. This new Promise resolves or rejects as soon as one of the input Promises resolves or rejects, whichever occurs first.

const promise1 = new Promise((resolve, reject) => {
  setTimeout(resolve, 500, 'foo');
});

const promise2 = new Promise((resolve, reject) => {
  setTimeout(reject, 100, 'bar');
});

Promise.race([promise1, promise2])
  .then(value => console.log(value))
  .catch(error => console.log(error)); // Output: bar
  • Promise.any: That takes an iterable (such as an array) of Promises and returns a new Promise that is fulfilled with the value of the first resolved Promise in the iterable.
const promises = [
  Promise.reject('Error 1'),
  Promise.resolve('Success 1'),
  Promise.reject('Error 2'),
  Promise.resolve('Success 2'),
];

Promise.any(promises)
  .then(result => console.log(result)) // Success 1
  .catch(error => console.log(error)); // AggregateError: All Promises were rejected
  1. Conclusion:

    A Promise is like a placeholder for a value that will be available sometime in the future, and you can write code that responds to that value once it's ready.