Open In App

What are the states of promises in ES6 ?

In this article, we will discuss the basic details associated with the promises followed by various states of promises in ES6.

Let us first understand some basic details which are associated with promises.



Promises:

Syntax:



The following syntax can be used for declaring a promise:

// This is how we could initialize
// or set up our promise object
let promise_object = new Promise();

States of Promises:

Syntax:

The following syntax can be used for setting up the states of promises:

// At a time either a promise gets resolved
// or reject but not both.
let promise_object = new Promise(resolve, reject);

Now, we have understood the basic details associated with the promises followed by states of promises, its high time to some examples which would help us to understand all the things in a better manner.

Example 1:




let promise = new Promise((resolve, reject) => {
  resolve("Hello World.... This is a Promise");
})
 
  // After promise getting successfully
  // executed, data gets printed
  .then((data) => console.log(data))
   
  // If any error comes in between then
  // it gets printed with the help of
  // catch block
  .catch((error) => console.log(error));

Output:

Hello World.... This is a Promise

Example 2: 




let promise = new Promise((resolve, reject) => {
  reject("Oops..!!! An Error Occurred");
})
 
  // Here .then() method has no significance
  // since it is being resolved by catch block
  .then((data) => console.log(data))
 
  // Error message will be displayed by
  // this catch() block
  .catch((error) => console.log(error));

Output:

Oops..!!! An Error Occurred

Article Tags :