Everything about Promise in JavaScript
Hello everyone,
Today I am going to write about promise in JavaScript. This is most asking question from interviewer and lot of people struggle in promise and how its working behind the scene and how many method in promise. this blog is cover all the method of promise. If you don't know about promise then this blog is very helpful for you.
Let's start....
What is promise?
The promise is an object represents the either resolve or reject. It handles asynchronous operation.
A Promise has three state-
- pending: this is initial state, neither fulfilled nor rejected.
- fulfilled: means that the operation was completed successfully.
- rejected: means that the operation failed.
A pending promise can either be fulfilled with a value or rejected with a reason (error).
During these operation we have .then method attached with the promise for fulfilled and .catch for handler the error if promise is failure.
The methods Promise.prototype.then(), Promise.prototype.catch(), and Promise.prototype.finally() are used to associate further action with a promise that becomes settled.
For example:
fetch("url").then(response=>response.json()).
then(data=>console.log(data))
.catch(error=>console.log(error))
This is basic example of promise which we are fetch the url so first it will go to the network. JavaScript does wait for sometime for response and once response is coming then it will convert it into json after then it will return the data. the whole process is happen asynchronously.
Promises are the ideal choice for handling asynchronous operations in the simplest manner. They can handle multiple asynchronous operations easily and provide better error handling than callbacks and events.
What is chaining
Callback functions have been used alone for asynchronous operations in JavaScript for many years. But in some cases, using Promises can be a better option.
If there are multiple async operations to be done and if we try to use good-old Callbacks for them, we’ll find ourselves quickly inside a situation called callback hell or paramid .
firstRequest(function(response) {
secondRequest(response, function(nextResponse) {
thirdRequest(nextResponse, function(finalResponse) {
console.log('Final response: ' + finalResponse);
}, failureCallback);
}, failureCallback);
}, failureCallback);
How to create promise object constructor
const myPromise = new Promise((resolve, reject) => {
if(condition) {
resolve('Promise is resolved successfully.');
} else {
reject('Promise is rejected');
}
});
It takes two parameters, one for success (resolve) and one for fail (reject).we can put the condition either promise is resolved or rejected
.then for resolve the promise
myPromise.then((message) => {
console.log(message);
});
Why Promise
Prior to promises events and callback functions were used but they had limited functionalities and created unmanageable code. Multiple callback functions would create callback hell that leads to unmanageable code. Also it is not easy for any user to handle multiple callbacks at the same time. Events were not good at handling asynchronous operations.
There are some more methods in promise-
- Promise.all()
- Promise.allSettled()
- Promise.any()
- Promise.race()
Promise.all()
The Promise.all() method takes an iterable of promises as an input. It returns a single Promise that resolves when all of the promises passed as an iterable, which have resolved or when the iterable contains no promises.
In simple way, if any of the passed-in promises reject, the Promise.all() method asynchronously rejects the value of the promise that already rejected, whether or not the other promises have resolved.
Promise.all( iterable )
const promise1 = Promise.resolve(5);
const promise2 = 62;
const promise3 = new Promise((resolve, reject) => {
setTimeout(resolve, 100, 'hello');
});
Promise.all([promise1, promise2, promise3]).then((values) => {
console.log(values);
});
// expected output: Array [5, 62, "hello"]
Parameters: This method accepts a single parameter iterable which takes an array of promises or a normal array which contains some objects.
Return values: It follows some rules to return a single promise:
If passed argument is empty, it returns a Promise that already resolved.
If passed iterable contains no promises, it returns a Promise that resolved asynchronously.
For all other cases, it returns a pending Promise.
Promise.allSettled()
The Promise.allSettled() method returns a promise that resolves after all of the given promises have either fulfilled or rejected.
Promise.allSettled(iterable);
const promise1 = Promise.resolve(3);
const promise2 = new Promise((resolve, reject) => setTimeout(reject, 100, 'foo'));
const promises = [promise1, promise2];
Promise.allSettled(promises).
then((results) => results.forEach((result) => console.log(result.status)));
// expected output:
// "fulfilled"
// "rejected"
Parameters: This method accept a single parameter iterable which takes an array of promises or a normal array which contains some objects.
Return Value: This method returns the following values:
If passed argument is empty, it returns a Promise that already resolved.
For all other cases, it returns a pending Promise, along with the status as well as the values of all promises which are passed inside it individually.
Promise.any()
Promise.any() takes an iterable of Promise objects. It returns a single promise that resolves as soon as any of the promises in the iterable fulfills, with the value of the fulfilled promise. If no promises in the iterable fulfill (if all of the given promises are rejected), then the returned promise is rejected with an error
Promise.any(iterable);
const promise1 = Promise.reject(0);
const promise2 = new Promise((resolve) => setTimeout(resolve, 100, 'fast'));
const promise3 = new Promise((resolve) => setTimeout(resolve, 500, 'slow'));
const promises = [promise1, promise2, promise3];
Promise.any(promises).then((value) => console.log(value));
// expected output: "fast"
Parameters iterable An iterable object, such as an Array.
Return value
An already rejected Promise if the iterable passed is empty.
An asynchronously resolved Promise if the iterable passed contains no promises.
A pending Promise in all other cases. This returned promise is then resolved/rejected asynchronously (as soon as the stack is empty) when any of the promises in the given iterable resolve, or if all the promises have rejected.
Promise.race()
The Promise.race() method returns a promise that fulfills or rejects as soon as one of the promises in an iterable fulfills or rejects, with the value or reason from that promise.
Promise.race(iterable);
const promise1 = new Promise((resolve, reject) => {
setTimeout(resolve, 800, 'first');
});
const promise2 = new Promise((resolve, reject) => {
setTimeout(resolve, 300, 'second');
});
Promise.race([promise1, promise2]).then((value) => {
console.log(value);
// Both resolve, but promise2 is faster
});
// expected output: "second"
Parameters
An iterable object, such as an Array. See iterable.
Return value
A pending Promise that asynchronously yields the value of the first promise in the given iterable to fulfill or reject.
Conclusion
This is all about promise so I am pretty sure that you know all about promises and clear idea about promise like how to use , why promises, error handling in promises, different methods for promises.
Thanks you everyone
🙏
Happy codding