JavaScript, asynchronous programming and Promises

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

Until now, you have only worked with regular values. You’ve created a variable or constant…


This content originally appeared on DEV Community and was authored by Coderslang: Become a Software Engineer

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

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 some time has to pass first? 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
  • Or 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?

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.

const userCount = getUserCount();

console.log(userCount); // Promise {<pending>}
Enter fullscreen mode Exit fullscreen mode

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.

const userCount = getUserCount();
const handleSuccess = (result) => {
  console.log(`Promise was fulfilled. Result is ${result}`);
}

userCount.then(handleSuccess);
Enter fullscreen mode Exit fullscreen mode

And for error handling - catch.

const handleReject = (error) => {
  console.log(`Promise was rejected. The error is ${error}`);
}

userCount.catch(handleReject);
Enter fullscreen mode Exit fullscreen mode

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.

const userCount = getUserCount();
const handleSuccess = (result) => {
  console.log(`Promise was fulfilled. Result is ${result}`);
}

const handleReject = (error) => {
  console.log(`Promise was rejected. The error is ${error}`);
}

userCount.then(handleSuccess).catch(handleReject);
Enter fullscreen mode Exit fullscreen mode

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.

try {
  console.log(getUserData(userId));
} catch (e) {
  handleError(e);
}
Enter fullscreen mode Exit fullscreen mode

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.

try {
  fetchUserData(userId).then(console.log);
} catch (e) {
  handleError(e);
}
Enter fullscreen mode Exit fullscreen mode

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?

try {
  fetchUserData(userId).then(console.log);
} catch (e) {
  handleError(e);
} finally {
  console.log('finally');
}
Enter fullscreen mode Exit fullscreen mode

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().

fetchUserData(userId).then(console.log).catch(handleError);
Enter fullscreen mode Exit fullscreen mode

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

Here's an interesting coding interview question on handling errors in javascript promise chains.


This content originally appeared on DEV Community and was authored by Coderslang: Become a Software Engineer


Print Share Comment Cite Upload Translate Updates
APA

Coderslang: Become a Software Engineer | Sciencx (2021-02-18T13:54:36+00:00) JavaScript, asynchronous programming and Promises. Retrieved from https://www.scien.cx/2021/02/18/javascript-asynchronous-programming-and-promises/

MLA
" » JavaScript, asynchronous programming and Promises." Coderslang: Become a Software Engineer | Sciencx - Thursday February 18, 2021, https://www.scien.cx/2021/02/18/javascript-asynchronous-programming-and-promises/
HARVARD
Coderslang: Become a Software Engineer | Sciencx Thursday February 18, 2021 » JavaScript, asynchronous programming and Promises., viewed ,<https://www.scien.cx/2021/02/18/javascript-asynchronous-programming-and-promises/>
VANCOUVER
Coderslang: Become a Software Engineer | Sciencx - » JavaScript, asynchronous programming and Promises. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2021/02/18/javascript-asynchronous-programming-and-promises/
CHICAGO
" » JavaScript, asynchronous programming and Promises." Coderslang: Become a Software Engineer | Sciencx - Accessed . https://www.scien.cx/2021/02/18/javascript-asynchronous-programming-and-promises/
IEEE
" » JavaScript, asynchronous programming and Promises." Coderslang: Become a Software Engineer | Sciencx [Online]. Available: https://www.scien.cx/2021/02/18/javascript-asynchronous-programming-and-promises/. [Accessed: ]
rf:citation
» JavaScript, asynchronous programming and Promises | Coderslang: Become a Software Engineer | Sciencx | https://www.scien.cx/2021/02/18/javascript-asynchronous-programming-and-promises/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.