Until now, you have only worked with regular values. You’ve created a variable or constant, saved something there, and it was immediately available for use. For example, you could have printed it to the console.
But what if the value does not appear immediately, but rather take time to appear? We often get data from a database or an external server. These operations take time and there are two ways to work with them:
- We can try to block the execution of the program until we receive the data.
- We can continue the execution and deal with the data later when it appears.
This is not to say that one method is definitely better than the other. Both suit different needs as we need different behavior in different situations.
If the data you are waiting for is critical to moving forward, then you need to block the execution and you can’t get around it. And if you can postpone the processing, then, of course, it’s not worth wasting time, because you can do something else.
A promise is a special type of object that helps you work with asynchronous operations.
Many functions will return a promise to you in situations where the value cannot be retrieved immediately.
In this case,
getUserCount is the function that returns a
Promise. If we try to immediately display the value of the
userCount variable, we get something like
This will happen because there is no data yet and we need to wait for it.
A promise can be in several states:
- **Pending** – response is not ready yet. Please wait.
- **Fulfilled** – response is ready. Success. Take the data.
- **Rejected** – an error occurred. Handle it.
With the **pending** state, we can’t do anything useful, just wait. In other cases, we can add handler functions that will be called when a promise enters the fulfilled or rejected state.
To handle the successful receipt of data, we need a
And for error handling we use
Please note that the
getUserCount function returns a promise, so we cannot directly use
userCount. To do something useful with the data when it appears, we need to add handlers to the
catch functions that will be called in case of success or error.
catch functions can be called sequentially. In this case, we will take care of both success and failure.
Error Processing in JS Promises
Suppose we have a
getUserData(userId) function that returns information about the user or throws an error if there are some problems with the
Previously, we added the regular
catch and handled the error in the catch block.
But errors that occur in asynchronous code inside promises cannot be caught with regular
Let’s try to replace the synchronous function
getUserData(userId), which immediately returns the result, with the asynchronous one
fetchUserData(userId), which returns a promise.
We want to keep the behavior the same – display the result if successful, or handle an error if it occurs.
But we won’t succeed. There are no issues with the synchronous code, so the execution will continue. But when an unhandled error occurs in asynchronous code, we will receive an
UnhandledPromiseRejection and our program will end.
To better understand the order of execution of the program, let’s add a
finally block. It will always run (as expected), but will it run before or after
Let’s try this one step-by-step:
- In the
tryblock we call the
fetchUserDatafunction, which returns a
catchblock is ignored because there were no errors in the
tryblock. Asynchronous execution hasn’t run yet!
finallyline is displayed on the screen.
- An error occurs in the asynchronous code and we see the error message in the console –
To avoid unhandled rejections in Promises, you should always handle them in
The code became shorter, cleaner, and we got rid of unexpected errors that were breaking our code.
Credit: Source link