Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

Sorry, you do not have permission to ask a question, You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please type your username.

Please type your E-Mail.

Please choose an appropriate title for the post.

Please choose the appropriate section so your post can be easily searched.

Please choose suitable Keywords Ex: post, video.

Browse

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Logo Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Logo

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Navigation

  • Home
  • About Us
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • About Us
  • Contact Us
Home/ Questions/Q 7382

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Latest Questions

Author
  • 60k
Author
Asked: November 28, 20242024-11-28T03:17:07+00:00 2024-11-28T03:17:07+00:00

JavaScript, asynchronous programming and Promises

  • 60k

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.

Learn Full Stack JavaScript

beginnerscodenewbiejavascriptwebdev
  • 0 0 Answers
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

Sidebar

Ask A Question

Stats

  • Questions 4k
  • Answers 0
  • Best Answers 0
  • Users 1k
  • Popular
  • Answers
  • Author

    How to ensure that all the routes on my Symfony ...

    • 0 Answers
  • Author

    Insights into Forms in Flask

    • 0 Answers
  • Author

    Kick Start Your Next Project With Holo Theme

    • 0 Answers

Top Members

Samantha Carter

Samantha Carter

  • 0 Questions
  • 20 Points
Begginer
Ella Lewis

Ella Lewis

  • 0 Questions
  • 20 Points
Begginer
Isaac Anderson

Isaac Anderson

  • 0 Questions
  • 20 Points
Begginer

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help

Footer

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise

Querify Question Shop: Explore, ask, and connect. Join our vibrant Q&A community today!

About Us

  • About Us
  • Contact Us
  • All Users

Legal Stuff

  • Terms of Use
  • Privacy Policy
  • Cookie Policy

Help

  • Knowledge Base
  • Support

Follow

© 2022 Querify Question. All Rights Reserved

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.