Know the promises in JavaScript
0 2439
Hi Developers,
Thank you for visiting this blog. The blog will discuss the Promises in JavaScript. The contents of this article carries the Introduction to Promise, Working of Promises, Rules of Promise, properties of Promise, and creation of Promise along with an example.
However, if you are not clear about the insights of JavaScript, you can Learn JavaScript Online that will help you to get your basics clear.
Introduction to Promises in JavaScript
Basically, Promises in JavaScript refer to an object, responsible for creating one value in the upcoming time. It may create a resolved value, or probably, it would produce a reason why it is not resolved. This promise in JavaScript can be possible in one of the 3 states.
We can consider Promises as anxious that means Promise will perform the task whatever you assign it once it is requested. The icing on the cake is, Promises are the savior from well known "callback hell". It makes the code easy to read and can be understood efficiently and trouble free.
What is Callback hell?
Callback hell in JavaScript occurs when there are multiple nested callbacks in one code. The major reason for this is due to the mistake of programmer to handle callbacks and can be solved through three major ways such as:
a) handling every single error in the code
b) keeping the code shallow
c) using modules
Working of Promises in JavaScript
As we read in upper paragraphs that Promise in JavaScript is an object that would be returned simultaneously via an asynchronous function. It will be in one of 3 potential states:
1. In fulfilled state, onFulfilled is going to be called.
2. In rejected state, onRejected is going to be called.
3. In pending state, it is neither rejected nor fulfilled.
A promise is finally settled if it is not in progress (either rejected or resolved). Sometimes, people use settled or resolved state to mean something very similar as 'not pending'.
When settled, a promise cannot be resettled, recalling the reject() or resolve() will have no impact. The immutable nature of a settled promise is a significant feature.
Native Promises in JavaScript do not detect promise state. Instead, it is up to you to consider the promise as black box. Only the function responsible for issuing the promise will be aware of the promised status of access to get reject or resolve.
Here is a feature that uses a Promise, and which will be resolved after a particular time delay:
1. const wait = time => new Promise((resolve) => setTimeout(resolve, time));
2. wait (3000).then()) => console.log('Hi!'));
Rules of Promise in JavaScript
A standard for Promise was characterized by the Promises / A + specification network. There are numerous implementations, including standard ECMAScript JavaScript promises.
The promises in JavaScript must follow a particular set of principles:
a) A principal or "thenable" is an element that provides a consistent standard-compliant .then() method.
b) A pending promise may change to a rejected or fulfilled status.
c) A rejected or fulfilled promise is settled and must not be advanced to another state.
d) When a promise is settled, it must contain a value (which may not be clear). That value should not convert.
Properties of Promises in JavaScript
* Promise.length
It has a length property which always contains value 1.
* Promise.prototype
This property is responsible for showing promise constructor prototypes.
Creating a Promise in JavaScript
we will discuss the creation of Promise in JavaScript. Before proceeding, you must know that the promise object is created with the help of its constructor and new keywords. Moreover, this particular constructor is known as "Executor Function". It is a must for this function to carry two functions as parameters.
The primary function that is (resolve) is used when the asynchronous task is concluded effectively and delivers the result as a value.
Secondly, the (rejected) function is used at the time of the failure of the task and produces the reason for the same. It is generally an error object.
One example has been done for you to help you understand creation of Promise. Let's walk through it:
1. const myFirstPromise = new Promise((resolve, reject) => { 2. // this will asynchronously call any one of them 3. // 4. // resolve(value); // for the fulfilled 5. // or 6. // reject("reason of failure"); // for the rejected 7. })
In order to integrate the promise feature into any JavaScript function, we simply return a promise:
1. function FirstAsyncFunction(url) { 2. return new Promise((resolve, reject) => { 3. const xhr = new XMLHttpRequest(); 4. xhr.open("GET", url); 5. xhr.onload = () => resolve(xhr.responseText); 6. xhr.onerror = () => reject(xhr.statusText); 7. xhr.send(); 8. }); 9. }
Wasn't it easy ? I guess you are now quite familiar with creation of promise.
Let's walk through another example of promise in JavaScript.
1. let examplePromise = new Promise((resolve, reject) => { 2. // resolve() will be called when the asynchronous process is successful otherwise reject() will be called. 3. // The setTimeout(...) function has been used to simulate the asynchronous code. 4. setTimeout(function(){ 5. resolve("Success!"); //if the asynchronous process is successful 6. }, 250); 7. }); 8. examplePromise.then((succesAlert) => { 9. // successAlert is the message which is passes in the resolve() function 10. // there is no compulsion of it being a string value but as the return is successAlert, it is recommended to use a string value. 11. console.log("Congratulations! " + successAlert); 12. });
Point to be noted:
Please keep in mind that a promise is considered settled only if it is rejected or fulfilled. In case of pending, it will not be considered as settled. Besides, the term resolved with Promises means the required promise is locked to match up with another promise.I hope this blog has taken you through the better understanding promises in JavaScript. Moreover, you can also go for Top 30 JavaScript Interview Questions if you are looking for career opportunities in this field.
Share:
Comments
Waiting for your comments