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 5826

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

Author
  • 60k
Author
Asked: November 27, 20242024-11-27T12:52:08+00:00 2024-11-27T12:52:08+00:00

Asynchronous JavaScript 101

  • 60k

This blog post was originally published in Tes Engineering blog.

Here is a short recap of some fundamentals of using asynchronous JavaScript with some practical examples.

Why do I need to use asynchronous code again?

JavaScript by its nature is synchronous. Each line is executed in the order it appears in the code. It’s also single threaded, it can only execute one command at a time.

If we have an operation that takes some time to complete, we are effectively blocked waiting for it. A couple of common scenarios where this could happen are calling an API and waiting for a response, or querying a database and waiting for the results. Ultimately the impact of this is a slow and frustrating user experience, which can lead to users dropping off your website.

Asynchronous programming offers a way to bypass the synchronous single threaded nature of JavaScript, enabling us to execute code in the background.

Promises

Promises enable asynchronous programming in JavaScript. A promise creates a substitute for the awaited value of the asynchronous task and lets asynchronous methods return values like synchronous methods. Instead of immediately returning the final value, the asynchronous method returns a promise to supply the value at some future point.

Let's look at a couple of common ways of implementing Promises. The sample code is extracted from a toy project Security Dashboard I’m working on, more here for the curious.

Chained Promises

const fetchLatestDevToNewsPromiseChaining = () => {   return fetch('https://dev.to/api/articles?per_page=5&tag=security')     .then(response => response.json())     .then(latestArticles => keyDevToInfo(latestArticles))     .catch(err) }; 
Enter fullscreen mode Exit fullscreen mode

JavaScript’s built in Fetch API returns a promise object which we can then ‘chain’ promise methods on to, in order to handle the response.

.then() passes the return value of its callback to the function in the subsequent .then(), whilst .catch() handles a rejected promise. We can keep ‘chaining’ on more handling of the results by adding more promise methods.

Async / await

const fetchLatestDevToNewsAsyncAwait = async () => {   try {     const response = await fetch("https://dev.to/api/articles?per_page=5&tag=security")     const latestArticles = await response.json()     return keyDevToInfo(latestArticles)   } catch (err) {     return err   } } 
Enter fullscreen mode Exit fullscreen mode

The other common approach is to use async / await. We use the keyword async on the function declaration and then await immediately before the request to the API. Rather than using the promise methods to handle the response, we can simply write any further handling in the same way as any other synchronous JavaScript.

As we’re not using promise methods here we should handle any rejected promises using a try / catch block.

What you’ll notice in both cases is that we don’t need to literally create the Promise object: most libraries that assist with making a request to an API will by default return a promise object. It’s fairly rare to need to use the Promise constructor.

Handling promises

Whether you’re using chained promises or async / await to write asynchronous JavaScript, a promise will be returned, and so when calling the function wrapping the asynchronous code we also need to settle the promise to get the value back.

There are some ways these can be handled via built in iterable methods from JavaScript, here are a few very handy ones for settling results of multiple promises:

Promise.all

Promise.all([fetchLatestDevToNewsPromiseChaining(), fetchLatestDevToNewsAsyncAwait()])   .then(([chained, async]) => {     createFile([...chained, ...async])   })  
Enter fullscreen mode Exit fullscreen mode

Promise.all is a good option for asynchronous tasks that are dependent on another. If one of the promises is rejected, it will immediately return its value. If all the promises are resolved you’ll get back the value of the settled promise in the same order the promises were executed.

This may not be a great choice if you don’t know the size of the array of promises being passed in, as it can cause concurrency problems.

Promise.allSettled

Promise.allSettled([fetchLatestDevToNewsPromiseChaining(), fetchLatestDevToNewsAsyncAwait()])   .then(([chained, async]) => {     createFile([...chained, ...async])   }) 
Enter fullscreen mode Exit fullscreen mode

Promise.allSettled is handy for asynchronous tasks that aren’t dependent on one another and so don’t need to be rejected immediately. It’s very similar to Promise.all except that at the end you’ll get the results of the promises regardless of whether they are rejected or resolved.

Promise.race

Promise.race([fetchLatestDevToNewsPromiseChaining(), fetchLatestDevToNewsAsyncAwait()])   .then(([chained, async]) => {     createFile([...chained, ...async])   }) 
Enter fullscreen mode Exit fullscreen mode

Promise.race is useful when you want to get the result of the first promise to either resolve or reject. As soon as it has one it will return that result – so it wouldn’t be a good candidate to use in this code.

So … should I use chained promises or async / await?

We’ve looked at two common approaches for handling asynchronous code in JavaScript: chained promises and async / await.

What’s the difference between these two approaches? Not much: choosing one or the other is more of a stylistic preference.

Using async / await makes the code more readable and easier to reason about because it reads more like synchronous code. Likewise, if there are many subsequent actions to perform, using multiple chained promises in the code may be harder to understand.

On the other hand, it could also be argued that if it’s a simple operation with few subsequent actions chained then the built in .catch() method reads very clearly.

Whichever approach you take, thank your lucky stars that you have the option to avoid callback hell!

beginnersjavascriptnodewebdev
  • 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 2k
  • Popular
  • Answers
  • Author

    ES6 - A beginners guide - Template Literals

    • 0 Answers
  • Author

    Understanding Higher Order Functions in JavaScript.

    • 0 Answers
  • Author

    Build a custom video chat app with Daily and Vue.js

    • 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.