What are promises in JavaScript? Explain with example.

What is a promise?

A Promise is an object that represents the fulfillment or failure of an asynchronous operation.

Why do we need Promise?

  • Promise objects handle asynchronous operations
  • It provides the ability to write cleaner code by reducing the call-back hell
  • It allows errors to be passed down the chain and handled in one common place so that the layers of error handling can be easily avoided

What are the states of promise?

A Promise is in one of these states:

  • pending: initial state, neither fulfilled nor rejected
  • fulfilled: meaning that the operation completed successfully
  • rejected: meaning that the operation failed

Example of promise:

let promiseToWriteReactApp = new Promise(function(resolve, reject){
   isWritten = true;  // hardcoded to true 
   (isWritten) ? resolve('resolved') : reject('rejected');
})

promiseToWriteReactApp.then(function(fromResolve){
   console.log(fromResolve);
}).catch(function(fromReject){
   console.log(fromReject);
})

Promise methods:

There are 6 methods of JavaScript Promise class as of April 2021. Those methods are:

  • Promise.all
  • Promise.allSettled
  • Promise.race
  • Promise.any
  • Promise.reject
  • Promise.resolve

Among all the promise methods Promise.all method is the most used.

Source:
Share