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 :)
Similar Reads
Promises in NodeJS
Promises are a fundamental concept in asynchronous programming in JavaScript, especially in NodeJS, where non-blocking I/O operations are key to performance. Promises allow us to handle asynchronous operations more efficiently than traditional callback functions, leading to cleaner, more readable co
8 min read
std::promise in C++
In C++ multithreading, a thread is the basic unit that can be executed within a process and to communicate two or more threads with each other, std::promise in conjunction with std::future can be used. In this article, we will discuss the std::promise in C++ and how to use it in our program. What is
3 min read
ReactJS ES6
ES6, also known as ECMA script 2015 is a scripting language which is based on specification and standardization by ECMA International Company in ECMA-262 and ISO/IEC 1623. It is the sixth edition of the ECMAScript language specification standard. It was created to standardize JavaScript language to
6 min read
JavaScript Promise
JavaScript Promises make handling asynchronous operations like API calls, file loading, or time delays easier. Think of a Promise as a placeholder for a value that will be available in the future. It can be in one of three statesPending: The task is in the initial state.Fulfilled: The task was compl
4 min read
NodeJS Promise Chaining
Node.js is great at handling tasks that don't need to happen instantly, like fetching data from a website. Promise chaining helps you manage these tasks in a specific order, one after the other.What is Promise Chaining? Promise chaining in Node.js allows you to execute multiple asynchronous operatio
4 min read
Futures and Promises in Scala
1. Explanation of Futures and Promises in Scala:Futures:In Scala, asynchronous computations are represented using futures. They are used to manage lengthy calculations, including requesting information over a network or retrieving data from a database. The outcome of an asynchronous computation is i
2 min read
Ember.js Promise then() Method
Ember.js is an open-source JavaScript framework used for developing large client-side web applications which is based on Model-View-Controller (MVC) architecture. Ember.js is one of the most widely used front-end application frameworks. It is made to speed up development and increase productivity. C
2 min read
ES6 Tutorial
.custom-container-for-toc { width: 100%; max-width: 1200px; } .section { margin-bottom: 20px; } .section-title { font-weight: bold; margin-bottom: 10px; } .section-items { display: flex; flex-wrap: wrap; gap: 10px; } .section-items a { display: block; width: calc(32% - 10px); overflow: hidden; text-
5 min read
Node.js Projects
Node.js is one of the most popular JavaScript runtime environments widely used in the software industry for projects in different domains like web applications, real-time chat applications, RESTful APIs, microservices, and more due to its high performance, scalability, non-blocking I/O, and many oth
9 min read
Ember.js Promise catch() Method
Ember.js is an open-source JavaScript framework used for developing large client-side web applications which are based on Model-View-Controller (MVC) architecture. Ember.js is one of the most widely used front-end application frameworks. It is made to speed up development and increase productivity.
2 min read