Promises are a way to implement asynchronous programming in JavaScript(ES6 which is also known as ECMAScript-6). A Promise acts as a container for future values. Like if you order any food from 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 uses callbacks, but there is a problem using the callback which is callback hell (multiple or dependent callbacks) 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 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. In simple words, having multiple callbacks in the code increases the complexity of the code in terms of readability, executability, and many other terms. This excessive nesting of callbacks is often termed Callback Hell.
Example: Callback Hell.
javascript
f1( function (x){ f2(x, function (y){ f3(y, function (z){ ... }); }); }); |
To deal with this problem, we use Promises instead of callbacks.
Making Promises: A Promise is 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 from real life itself, 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 been fulfilled or rejected
Syntax:
const promise = new Promise((resolve,reject) => {....});
Example:
javascript
const myPromise = new Promise((resolve, reject) => { if (Math.random() > 0) { resolve( 'Hello, I am positive number!' ); } reject( new Error( 'I failed some times' )); }) |
Callbacks to Promises: There are two types of callbacks that are used for handling promises .then() and .catch(). It can be used for handling promises in case of fulfillment (the promise is kept) or rejection (the promise is broken).
JavaScript .then() Method: Invoked when a promise is kept or broken. It can be chained to handle the fulfillment or rejection of a promise. It takes in two functions as parameters. The first one is invoked if the promise is fulfilled and the second one(optional) is invoked if the promise is rejected.
Example: Handling Promise rejection using .then()
javascript
var promise = new Promise((resolve, reject) => { resolve( 'Hello, I am a Promise!' ); }) promise.then((promise_kept_message) => { console.log(promise_kept_message); }, (error) => { // This function is invoked this time // as the Promise is rejected. console.log(error); }) |
Output:
Hello, I am a Promise!
JavaScript .catch() Method: This can be used for handling the errors(if any). It takes only one function as a parameter which is used to handle the errors (if any).
Example: Handling Promise rejection(or errors) using .catch()
javascript
const myPromise = new Promise((resolve, reject) => { if (Math.random() > 0) { console.log( 'resolving the promise ...' ); resolve( 'Hello, Positive :)' ); } reject( new Error( 'No place for Negative here :(' )); }); const Fulfilled = (fulfilledValue) => console.log(fulfilledValue); const Rejected = (error) => console.log(error); myPromise.then(Fulfilled, Rejected); myPromise.then((fulfilledValue) => { console.log(fulfilledValue); }). catch (err => console.log(err)); |
Output:
resolving the promise ... Hello, Positive :) Hello, Positive :)