What is Promise in JavaScript (ES)

February 13, 2020

What is Promise in JavaScript

What is Promise in JavaScript (ES)

A promise in Javascript is an object which represent the eventual completion or failure of an asynchronous operation. Promises represent a proxy for a value which are getting in some point in the future.

A promise can have 3 states which are the following:

  1. Pending: This is the initial state of the promise, the promise is now waiting for either to be resolved or rejected. For example, when are reaching out to the web with an AJAX request and wrapping the request in a promise. Then the promise will be pending in the time window in which the request is not returned.
  2. Fulfilled:When the operation is completed successfully, the promise is fulfilled. For example, when we are reaching out to be web using AJAX for some JSON data and wrapping it in a promise. When we are successfully getting data back the promise is said to be fulfilled.
  3. Rejected:When the operation has failed, the promise is rejected. For example, when we are reaching out to be web using AJAX for some JSON data and wrapping it in a promise. When we are getting a 404 error the promise has been rejected.

    Promise Constructor:

    We can create a promise in the following manner:

    let BitFrit = new Promise((res, rej) => {
     console.log('synchronously executed');
     if (Math.random() > 0.5) {
       res('Success');
     } else {
       rej('Error');
     }
    })
    
    
    BitFrit.then((val) => {
     console.log('asynchronously executed: ' + val);
    }).catch((err) => {
     console.log('asynchronously executed: ' + err);
    }).finally(() => {
     console.log('promise done executing');
    });

Written by Manoj Bhardwaj who lives and works in Mohali Punjab (India). My stackoverflow