Javascript Promise

js

Promises are used to handle asynchronous operations in JavaScript. They are easy to manage when dealing with multiple asynchronous operations.

The Promise object represents the eventual completion (or failure) of an asynchronous operation, and its resulting value.

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.

After knowing the state of the Promise object, it can be cosumed by the promise inbuilt methods .then() and .catch()

Promise.prototype.then():

then() is invoked when a promise is either resolved or rejected.

then() also invokes callback functions in order. So you can chain callback function using then() method.

Promise.prototype.catch():

catch() is invoked when a promise is either rejected or some error has occurred in execution.

Example:

let promise1 = () => {
   let p1 = new Promise(function(resolve, reject){
      setTimeout(function() {
         console.log('first promise has been created!');
         resolve({p1input: 'xxx'});
      }, 2000);
   });
   return p1;
};
 
 
let promise2 = (inputstring) => {
   let p2 = new Promise(function(resolve, reject){
      setTimeout(function() {
         console.log('second promise has been created!');
         resolve({p2input: inputstring.p1input + ' test'});
      }, 2000);
   });
   return p2;
};
 
let promise3 = (inputstring) => {
   let p3 = new Promise(function(resolve, reject){
      setTimeout(function() {
         console.log('third method completed');
         resolve({result: inputstring.p2input});
      }, 3000);
   });
   return p3;
};
 
firstMethod()
   .then(secondMethod)
   .then(thirdMethod);