In this article, we will try to understand few things which include promise creation (with the help of syntax for declaration and an example) as well as checking where exactly is rejected property stored for a promise in JavaScript.
Let us first have a look over the below-mentioned section that illustrates the syntax for declaring a promise and executing its result later catching the error, if caught so, in JavaScript.
Syntax: Following enlightened syntax, we may use in order to declare a promise in JavaScript:
new Promise((resolve, reject) => { // resolve() method or reject() method }).then((result) => { // Result }).catch((error) =>{ // Caught error })
Let us have a look over the below-illustrated example that will help us to understand the promise’s declaration as well as its proper execution in JavaScript.
Example: In this example, we will simply create a promise with the help of the above syntax of declaration, and then later with the help then() and catch() method we will execute the result and catch the error if caught so respectively.
Javascript
<script> let new_promise = new Promise((resolve, reject) => { resolve( "This topic is available on " + "neveropen platform...!!" ); }); new_promise .then((result) => { console.log(result); }) . catch ((error) => { console.log(error); }); </script> |
Output:
This topic is available on neveropen platform...!!
Where does the rejected property for Promise is stored?
Since JavaScript doesn’t provide any special explicit property or Public API (Application Programming Interface) through which we could externally identify that particular thing, so we may check the rejected property of the promise inside the internal promise’s object itself.
The following illustrated example along with its output will help us to identify where does actually the rejected property for a promise is stored in JavaScript:
Example: In this example, we will simply create a promise that will use the reject() method which then shows the rejected state of a promise along with a certain message passed inside the reject() method, and all of this we will see in browser’s console’s output itself where we will visualize this with pictorial representation.
Javascript
<script> let new_promise = new Promise((resolve, reject) => { reject( "Rejected Promise...!!" ); }); new_promise .then((result) => { console.log(result); }) . catch ((error) => { console.log(error); }); </script> |
Output:
As we may visualize from the above output (shown through the pictorial representation), under the promise’s internal object’s property named PromiseState, the rejected property of the promise is stored, and later when we have implemented catch in order to make our promise fulfilled then that PromiseState property’s value becomes Fulfilled. This is how we may check or visualize the state of a promise in JavaScript.