A promise is an object that may produce a single value some time in the future: either a resolved value, or a reason that it’s not resolved.
Real life example
“Imagine you are a kid. Your dad promises you that he will buy you a new toy next week”
That is a promise. A promise has 3 states:
- Pending: You don’t know if you will get the toy
- Fulfilled: Dad is happy and he will get you a toy
- Rejected: Your dad is not happy, he withholds the toy
What is Asynchronous programming?
In programming, we can simplify the definition of synchronous code as “a bunch of statements in sequence”; so each statement in your code is executed one after the other. This means each statement has to wait for the previous one to finish executing. Asynchronous code takes statements outside of the main program flow, allowing the code after the asynchronous call to be executed immediately without waiting.
State of Promise:
Let's create our first Promise and see how to consume it:
Promises are asynchronous!
Let's relate back to our real life example:
Probably you expected this as the output?
However, the actual output sequence is:
You, the kid, wouldn’t stop playing with your old toys while waiting for the new toy. Will you? That’s something we call asynchronous, the code will run without blocking or waiting for the result. Anything that need to wait for promise to proceed, you put that in
Why do we use Promise?
Prior to promise we had callbacks. A callback is a function that is to be executed after another function has finished executing — hence the name call back.
The above code snippet refers to a Callback hell since we nested the code four times. In order to escape from callback hell we use Promise.
Promise.all is a promise that takes an array of promises as an input and gets resolved when all the promises get resolved or any one of them gets rejected.
For instance, we have five promises, all make async requests such as fetching data from database, Promise.all will return a resolve or reject state based on the promises execution. Promise.all is itself a promise.
Error objects that are thrown inside promises, hence they won’t tell you anything about the sequence of actions which led to the error; all they’ll tell you is the file and line number where the error was created. So we need to use better error handling mechanism to log these errors.
If there are no errors .catch doesn’t trigger at all. But if any of the promises rejects (a network problem or invalid json or whatever), then it would catch it.
Promise.reject() returns a Promise that is rejected. It is highly used for debugging purposes and error catching.
You made it!
Top comments (0)