Promises is used to efficiently handle the asynchronous action of the JavaScript. Promise is introduced to avoid creation of unnecessary callback hell while handling asynchronous action.
For example, you are requesting a some sample data from the API through your program for the given position, if the position is valid you may expect the result, but if the position is not valid you may get error. Your program should be flexible enough to handle both the positive result and the negative result (nothing but the error).
Now, how can we write a program in JavaScript that will handle the asynchronous action and its unknown result efficiently? Here comes the promise.
Promise is basically a constructor function which takes another function (executor function) as an argument, out of which any number of promise object can be created. This executor function posses two callbacks to handle the success and to handle the failure.
The syntax of the promise will be as follows,
var myPromise = new Promise(function(resolve, reject){
//do some logic
});
Example:
var promise = new Promise(function(resolve, reject) {
var a = "fullstackadda.com";
var b = "fullstackadda.com"
if(a === b) {
resolve();
} else {
reject();
}
});
Now we have just created a promise for the asynchronous action, still we don’t know whether the promise will yield positive result or negative result, everything depends on the outcome of the asynchronous action.
A Promise has three states:
- pending : Neither fulfilled nor rejected
- fulfilled : if asynchronous action yields result, then promise moves to fulfilled state.
- rejected : if asynchronous action yields error, then the promise moves to rejected state.
Assume that we have obtained result from the outcome of asynchronous action, now how to carry forward this result to next step, now here comes the then() method of the promise object, which accepts two functions as argument similar to executor function, but here the user should define the function for fulfilled promise and rejected promise. Here the function should take into account that what should be done for fulfilled promise and what should be done for rejected promise.
var promise = new Promise(function(resolve, reject) {
var a = "fullstackadda.com";
var b = "fullstackadda.com"
if(a === b) {
resolve();
} else {
reject();
}
});
promise.
then(function () {
console.log('Success');
}).
catch(function () {
console.log('Error');
});
Success
Now we have successfully handled the asynchronous action and its result through promise.
Promise Chaining :
Combining multiple .then() .catch() to a single promise is called promise chaining.
const url = "https://fakestoreapi.com/";
let responseApi = fetch(url);
responseApi
.then((response) => {
return response.json();
})
.then((data) => {
console.log(data);
});
Why Promise chaining is required? Because in our program if there are multiple asynchronous action and if there is case where one asynchronous action is input to the other asynchronous action, then the resolved promise of first asynchronous action will passed to second promise through promise chaining.
- Advantages of Promises.
- Better defined and organized control flow of asynchronous logic.
- Enhanced readability.
- Better flow of control definition in asynchronous logic
- Better Error Handling
- disadvantages of Promises.
- It kills the purpose of asynchronous non-blocking I/O.
- We cannot return multiple arguments.