A promise is one of the most confusing concepts in javascript for someone new to Javascript. It may look quite complicated to understand at first sight, but it is quite simple and is not rocket science.
Promise in javascript is similar to promise in real life, like how we promise to do a task like cleaning the room, it is a guarantee that we are going to do something in the future.
Why do we need Promise?
Before Promise, callback functions were used for performing asynchronous operations. Since it was confusing and had limitations in functionality, Promise was introduced in ES6.
If there are multiple asynchronous 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.
A simple promise function
let promise = new Promise((resolve, reject) => {
let task_performed = true;
if(task_performed) {
resolve('Success!');
} else {
reject('Failed!');
}
});
Different states of Promise
The 3 states of promise object are:
- Pending
- Resolved
- Rejected
Pending: It is the initial state of the Promise before Promise succeeds or fails. When we request data from the server by using a Promise, it will be in pending mode until we receive our data.
Resolved: It is the state where a promise is fulfilled successfully. It's like when we use a promise to get data from the server, we get the resolved state when the data is successfully received.
Rejected: It is the state where a promise is not fulfilled due to some error.
The .then() method is called after a promise is resolved. We can use it to decide what to do with the resolved promise.
let promise = new Promise((resolve, reject) => {
let task_performed = true;
if(task_performed) {
resolve('Success!');
} else {
reject('Failed!');
}
});
promise.then((response) => console.log(response))
We also know that not all Promises will be resolved every time. What if the promise gets rejected? We use the .catch() method after a promise is rejected. It can be used for throwing a new error or logging the details to the console.
let promise = new Promise((resolve, reject) => {
let task_performed = true;
if(task_performed) {
resolve('Success!');
} else {
reject('Failed!');
}
});
promise.then((response) => console.log(response))
.catch((error) => console.log(error))
Top comments (0)