ES6 | Promises

Promises are a way to implement async programming in JavaScript(ES6). A Promise will become a container for future value. Like if you order any food on any site to deliver it to your place that order record will be the promise and the food will be the value of that promise. So the order details are the container of the food you ordered. Let’s explain it with another example. You order an awesome camera online. After your order is placed you receive a receipt of the order. That receipt is a Promise that your order will be delivered to you. The receipt is a placeholder for the future value namely the camera.

Promises used in JavaScript for asynchronous programming. For asynchronous programming, JavaScript used callbacks but there is a problem using the callback which is callback hell or Pyramid of Doom. Using the ES6 Promise will simply avoid all the problems associated with the callback.

Need of Promises: The Callbacks are great when dealing with basic cases. But in while developing a web application where you have a lot of code. Callbacks can be great trouble. In complex cases, every callback adds a level of nesting which can make your code really messy and hard to understand. This excessive nesting of callbacks is often termed as Callback Hell.

Example: Callback Hell



filter_none

edit
close

play_arrow

link
brightness_4
code

f1(function(x){
    f2(x, function(y){
        f3(y, function(z){ 
            ...
        });
    });
}); 

chevron_right


To deal with this problem, we use Promises instead of callbacks.

Making Promises: A Promise is basically created when we are unsure of whether or not the assigned task will be completed. The Promise object represents the eventual completion (or failure) of an async(asynchronous) operation and its resulting value. As the name suggests a Promise is either kept or broken.
A Promise is always in one of the following 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

Syntax:

const promise = new Promise((resolve,reject) => {....}); 

Example:

filter_none

edit
close

play_arrow

link
brightness_4
code

const myPromise = new Promise((resolve, reject) => {
    if (Math.random() > 0) {
        resolve('Hello, I am positive number!');
    }
    reject(new Error('I failed some times'));
})

chevron_right


Callbacks to Promises: There are two types of callbacks which are used for handling promises .then() and .catch(). It can be used for handling promises in case of fulfillment (promise is kept) or rejection (promise is broken).