JavaScript Promises

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. 

Prior to promises events and callback functions were used but they had limited functionalities and created unmanageable code. 
Multiple callback functions would create callback hell that leads to unmanageable code. Also it is not easy for any user to handle multiple callbacks at the same time.
Events were not good at handling asynchronous operations.

Promises are the ideal choice for handling asynchronous operations in the simplest manner. They can handle multiple asynchronous operations easily and provide better error handling than callbacks and events. In other words also, we may say that, promises are the ideal choice for handling multiple callbacks at the same time, thus avoiding the undesired callback hell situation. Promises do provide a better chance to a user to read the code in a more effective and efficient manner especially it that particular code is used for implementing multiple asynchronous operations. 


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
  5. Promise Object Properties

    A JavaScript Promise object can be:

    • Pending
    • Fulfilled
    • Rejected

    The Promise object supports two properties: state and result.

    While a Promise object is "pending" (working), the result is undefined.

    When a Promise object is "fulfilled", the result is a value.

    When a Promise object is "rejected", the result is an error object.

    • A promise can be created using Promise constructor.
      Syntax
    var promise = new Promise(function(resolve, reject){
         //do something
    });
    • Parameters 
      • Promise constructor takes only one argument which is a callback function (and that callback function is also referred as anonymous function too).
      • 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 

      • var promise = new Promise(function(resolve, reject) {
    •  const x="hyy";
    •    const y = "hello"
    •  if(x === y) {
    • resolve();
    •   } else {
    • reject();
    •   }
    •   });

    •    promise.
    • then(function () {
    • console.log('Success, You are a GEEK');
    • }).
    • catch(function () {
    • console.log('Some error has occurred');
    • });

    • Promise Consumers
      Promises can be consumed by registering functions using .then and .catch methods.

      1. then() 
      then() is invoked when a promise is either resolved or rejected. It may also be defined as a career which takes data from promise and further executes it successfully.

      Parameters: 
      then() method takes two functions as parameters. 

      1. First function is executed if promise is resolved and a result is received.
      2. Second function is executed if promise is rejected and an error is received. (It is optional and there is a better way to handle error using .catch() method

      Syntax:

      .then(function(result){
              //handle success
          }, function(error){
              //handle error
          })

      Example: Promise Resolved

      var promise = new Promise(function(resolve, reject) {
          resolve('promise fullfill');
      })
         
      promise
          .then(function(successMessage) {
             //success handler function is invoked
              console.log(successMessage);
          }, function(errorMessage) {
              console.log(errorMessage);
          })

      Output:

      promise fullfill

      Examples: Promise Rejected

      var promise = new Promise(function(resolve, reject) {
          reject('Promise Rejected')
      })
         
      promise
          .then(function(successMessage) {
              console.log(successMessage);
          }, function(errorMessage) {
             //error handler function is invoked
              console.log(errorMessage);
          })

      Output:

      Promise Rejected

      2. catch() 

      catch() is invoked when a promise is either rejected or some error has occurred in execution. It is used as an Error Handler whenever at any step there is a chance of getting an error.

      Parameters: 
      catch() method takes one function as parameter. 

      1. Function to handle errors or promise rejections.(.catch() method internally calls .then(null, errorHandler), i.e. .catch() is just a shorthand for .then(null, errorHandler) )

      Syntax:

      .catch(function(error){
              //handle error
          })

      Examples: Promise Rejected

      var promise = new Promise(function(resolve, reject) {
          reject('Promise Rejected')
      })
         
      promise
          .then(function(successMessage) {
              console.log(successMessage);
          })
          .catch(function(errorMessage) {
             //error handler function is invoked
              console.log(errorMessage);
          });

      Output:

      Promise Rejected

      Examples: Promise Rejected

      var promise = new Promise(function(resolve, reject) {
          throw new Error('Some error has occurred')
      })
         
      promise
          .then(function(successMessage) {
              console.log(successMessage);
          })
          .catch(function(errorMessage) {
             //error handler function is invoked
              console.log(errorMessage);
          });

      Output:

      Error: Some error has occurred

      Applications 

      1. Promises are used for asynchronous handling of events.
      2. Promises are used to handle asynchronous http requests.

Comments

Popular posts from this blog

Two Sum II - Input Array Is Sorted

Comparable Vs. Comparator in Java

Increasing Triplet Subsequence