What's a Promise in a real life scenario?
Let's skip the technical part and leave it for the end.
I'll try to explain in "human" words what a Javascript Promise is. I will go into some techincal details at the end.
Real World example
We have a parent and its child.
The child wants something sweet to eat. He asks his parent if he can have an icecream.
The parent replies "I'll get you an icecream, but first I will check if you cleaned your room.".
The child says: "Yes, I have cleaned my room".
The parent will go and check the room to see if the room is cleaned.
We will now have 2 possible outcomes:
- If the room is cleaned, the parent will GET the child an icecream.
- If the room is not cleaned, the parent will NOT GET the child an icecream.
Example explained
In the above example, the parent is the executor. The room check is the promise. The parent will check if the room is cleaned and will resolve the promise if the room is cleaned. If the room is not cleaned, the parent will reject the promise.
The child is the consumer. The child is the one who is waiting for the promise to be resolved or rejected. The child will consume the icecream if the promise is resolved. If the promise is rejected, the child will not consume the icecream.
Javascript example
Let's see how we can implement the above example in Javascript.
const parent = new Promise((resolve, reject) => {
// check if the room is cleaned
const isRoomCleaned = true;
if (isRoomCleaned) {
resolve('get icecream');
} else {
reject('dont get icecream');
}
});
The above code is the executor. The executor is the function that is passed to the Promise constructor. The executor takes 2 arguments, resolve and reject. The executor will resolve the promise if the room is cleaned and will reject the promise if the room is not cleaned.
const child = () => {
parent
.then((value) => {
console.log(value);
})
.catch((error) => {
console.log(error);
});
};
child();
Or with async/await
const child = async () => {
try {
const value = await parent;
console.log(value);
} catch (error) {
console.log(error);
}
};
child();
What's a Promise in technical terms
A Promise is an object that represents the eventual completion or failure of an asynchronous operation. A Promise is in one of these states:
- pending: initial state, neither fulfilled nor rejected.
- fulfilled: meaning that the operation was completed successfully.
- rejected: meaning that the operation failed.
I hope this article helped you better understand what a Promise is.