How to Create a Promises in JavaScript?

Hi everyone, welcome back. In this module, I will be discussing Promises in JavaScript. If you want to know about the features included in the latest version of JavaScript, then you can read our previous module in which I have discussed it. So, without any further delay, let’s get started to know Promises in JavaScript.

Promises in JavaScript

Promises in JavaScript

In JavaScript, promises are used for handling asynchronous operations. When dealing with several asynchronous activities, callbacks might create callback hell, which leads to unmanageable code, and then promises become easy to manage. Promises in JavaScript provide better handling of errors than events and callbacks. It was introduced in ECMAScript 2015 or ES6.

A JavaScript promise is like a real-world promise. A promise has 2 possible results: either it will be kept at the right moment or it will not. The same is true with JavaScript promises. When we define a promise in JavaScript, it is either resolved or rejected.

A promise is defined as an object that can produce a single value in the future: either a resolved value or a reason for an unresolved promise. It has two properties: state & result.

Now, let’s see what the states of JavaScript promises are.

What are the states of Promises in JavaScript?

Promises in JavaScript have three states:

  • Pending: Promise is neither resolved nor rejected.
  • Fulfilled or Resolved: Promise is completed. The resultant value is a resolved value.
  • Rejected: Promise is not fulfilled. The resultant value is an error object.

For example, when a user requests data from the server with a promise, it remains in a pending state till we are receiving our data. The promise will be resolved successfully if we acquire the requested information from the server. However, if we do not receive the information, then the Promise will be rejected.

Let’s now see how to create promises in JavaScript.

How to create a promise in JavaScript?

In JavaScript, a promise object can be created by using the Promise constructor.

Syntax
let promise = new Promise(function(resolve, reject){
//statements
});

The promise constructor takes a callback function as an argument. The callback function takes 2 parameters: resolve for fulfilled promise & reject for the failure of the promise.

The callback function inside the new Promise object is called the executor. The executor is automatically executed when a new promise is produced. A promise consists of producing code & consuming code.

A “producing code” is a set of statements that performs some operation & it takes time. It produces some results that will be used by the consuming code.

A “consuming code” is a set of statements that waits for the result from the producing code. A promise is a JavaScript object, which links the “production code” along with the “consumer code.”

let promise = new Promise(function(resolve, reject) {
// producing code
const a = "hello";
const b = "Hello"
  if(a === b) {
    resolve(); // call on fulfilled promise.
}
else {
  reject(); // call on rejected promise.
}
});

// consuming code, waiting for a promise to be resolved or fulfilled.
promise.then(function () {
  console.log('The promise is fulfilled.');
}).catch(function () {
  console.log('The promise is rejected.');
});

//Output
//The promise is rejected.

then() for a resolved promise

The then() method takes the callback function for the resolved promise as the first argument & the callback function for the rejected promise as the second argument.
After the promise is resolved, we can decide what to do next.
Syntax

.then(function(result){
// statements to be executed on fulfilled promise
}, function(error){
// statements to be executed on rejected promise
});

For example,

let promise = new Promise(function(resolve, reject) {
  resolve('Resolved Promise');
})
promise.then(function(success) {
  console.log(success);
},function(error) {
  console.log(error);
});
//Output
//Resolved Promis
let promise = new Promise(function(resolve, reject) {
  reject('Rejected Promise');
})
promise.then(function(success) {
  console.log(success);
},function(error) {
  console.log(error);
});
//Output
//Rejected Promise

catch() method for rejected promise

It is executed when some error occurs or a promise is rejected.

Syntax
.catch(function(error){
// handling error for rejected promise
});

For example,

let promise = new Promise(function(resolve, reject) {
  reject('Promise Rejected')
})

promise.then(function(success) {
  console.log(success);
}).catch(function(error) {
  console.log(error);
});
//Output
//Promise Rejected

How to convert promise to array in JavaScript?

We can convert a list of promises into an array by using the Promise.all() static methods in JavaScript. The Promise.all() Method takes an iterable of promises as an input, returning a single promise to an array of input promises. This returned promise will resolve when all input promises have been resolved or rejected if any of the input promises has been rejected.

const p1 = Promise.resolve(10);
const p2 = 50;
const p3 = new Promise((resolve, reject) => {
  setTimeout(resolve, 200, 'Hello');
});
Promise.all([p1, p2, p3]).then((value) => {
  console.log(value);
});

//Output
//Array [10, 50, "Hello"]

I hope this module will be beneficial & now you have got some basic knowledge of Promises in JavaScript & how to create promises. As a beginner, it will take some time to understand properly how promises work, but by practising it, you will get to know about it. In the next module, I will be discussing async & await in JavaScript. You can refer to our website for getting more informative modules like this.