d

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore.

15 St Margarets, NY 10033
(+381) 11 123 4567
ouroffice@aware.com

 

KMF

JavaScript, Asynchronous Programming, and Promises

In this tutorial, you’ll learn what promises are in JavaScript, which states JavaScript promises can be in, and how to handle asynchronous errors in JS promises.

If you’re already familiar with this topic, you might be interested in learning how to handle promise chains in JavaScript. 

Introduction

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.

What Is a JavaScript Promise Exactly?

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 Promise {<pending>}.

This will happen because there is no data yet and we need to wait for it.

Promise States in JavaScript

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 then function.

And for error handling we use catch.

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 then and catch functions that will be called in case of success or error.

The then and 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 userId parameter.

Previously, we added the regular try/catch and handled the error in the catch block.

But errors that occur in asynchronous code inside promises cannot be caught with regular try/catch.

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 UnhandledPromiseRejection?

Let’s try this one step-by-step:

  1. In the try block we call the fetchUserData function, which returns a Promise in the pending state.
  2. The catch block is ignored because there were no errors in the try block. Asynchronous execution hasn’t run yet!
  3. The finally line is displayed on the screen.
  4. An error occurs in the asynchronous code and we see the error message in the console – UnhandledPromiseRejectionWarning.

To avoid unhandled rejections in Promises, you should always handle them in .catch().

The code became shorter, cleaner, and we got rid of unexpected errors that were breaking our code.

Credit: Source link

Previous Next
Close
Test Caption
Test Description goes like this