By default, Fetch request returns Promise, but you might be wondering what the hell is that? Well, a Promise is an object that is being used for asynchronous operations. What do I mean by that?
Let’s walk through the image above:
Line 1: We declare a p variable, that holds an instance of a new Promise, which takes two parameters: when promise being resolved and when a promise is being rejected.
Line 2: Declared a basic test case
Line 3–7: Here is what’s happening under the hood, Basically if a condition is satisfied, we’re going to run the resolve function with a success message, otherwise if a promise is rejected we’re going to run the reject function with a failure message.
So now let’s pretend that statement above is our promise that we’ve got with a fetch request, on which you can chain .then() and .catch() methods. Let’s have a closer look:
Here we chained .then() and .catch() to our promise, and for simplicity sake, those examples are very basic, so let’s talk about it for a second:
As we’ve declared our promise gonna run either resolve or reject function based on some condition and if this condition is met it’ll run resolve function which will be returned in our .then() method. So basically if a is equal to 2 the return message will be “This is in the then Success”, and if a is not equal to then our promise will be rejected, and the reject method will be run and executed in our catch method which would result in this message “This is in the catch Failed”.
Before we move forward let’s have a look at three states of the promise:
- Pending, which is its initial state, means it’s neither rejected nor fulfilled.
- Fulfilled, meaning that the operation was completed successfully.
- Rejected, meaning that the operation failed.
In the picture above we have an illustration of all the states of promise, initialized with pending and then either fulfilled or rejected.
Let’s talk refected state in a little bit more details:
We can disregard the first two warnings since I purposefully made a typo in the request path. The last one states “Uncaught (in promise) TypeError: Failed to fetch. And this warning is very information that tells us that we didn’t catch our rejected state and didn't act on it. Let’s have a look at what happens if we’ll add a .catch() method to it.
As we can see it’s been caught by our catch method and we were alerted with an ‘error.message’ that tells us the reason why promise in the rejected state, in which we can go further and synchronously do things based on the state of the promise which is much easier and more convenient than dealing with callbacks function hell instead….