Promises are used to handle asynchronous operations in JavaScript. They are easy to manage when dealing with multiple asynchronous operations where callbacks can create callback hell leading to unmanageable code.

  • Benefits of Promises
    1. Improves Code Readability
    2. Better handling of asynchronous operations
    3. Better flow of control definition in asynchronous logic
    4. Better Error Handling  

 

  • A Promise has four states:
    • fulfilled: Action related to the promise succeeded
    • rejected: Action related to the promise failed
    • pending: Promise is still pending i.e not fulfilled or rejected yet
    • settled: Promise has fulfilled or rejected

var promise = new Promise(function(resolve, reject){ //do something });

Parameters

  • Promise constructor takes only one argument,a callback function.
  • Callback function takes two arguments, resolve and reject
  • Perform operations inside the callback function and if everything went well then call resolve.
  • If desired operations do not go well then call reject.
// javascript Promise
var myPromise=new Promise(function(resolve,reject){
  const x='hello';
  const y='hello';
  if(x===y){
    resolve();
  }
  else{
    reject();
  }
});
myPromise.then(function(){
  alert('Thank you this is promise resolve');
}).catch(function(){
  alert('Thank you this is promise reject');
});