ES6 | Promises - GeeksforGeeks

25 Mar, 2022
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 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. 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 as 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 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 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).
.then(): 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(function(resolve, reject) {    resolve('Hello, I am a Promise!');}) promise.then(function(promise_kept_message) {        console.log(promise_kept_message);            }, function(error) {            // This function is invoked this time        // as the Promise is rejected.        console.log(error); })
.catch() 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));
amansingla
JavaScript-ES
Picked
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to append HTML code to a div using JavaScript ?
How to Open URL in New Tab using JavaScript ?
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Top 10 Projects For Beginners To Practice HTML and CSS Skills