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>}
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);
And for error handling - catch
.
const handleReject = (error) => {
console.log(`Promise was rejected. The error is ${error}`);
}
userCount.catch(handleReject);
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);
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);
}
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);
}
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');
}
Let's try this one step by step:
- In the
try
block we call thefetchUserData
function, which returns aPromise
in thepending
state. - The
catch
block is ignored because there were no errors in thetry
block. Asynchronous execution hasn't run yet! - The
finally
line is displayed on the screen. - 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);
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
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/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.