Async and await in JavaScript - run several blocks of code in parallel

Get FREE Premium WordPress Blog Theme

Download Now
MinoPress Logo
  • Home
  • Products
      • Azi Theme - $24
        Azi Theme - $24Multipurpose Woocommerce Theme
      • Muskan <br> $19
        Muskan
        $19
        Multipurpose Woocommerce Theme
      • AAnglo - FREE
        AAnglo - FREELifestyle Blog WordPress Theme
      • Jusako - $19
        Jusako - $19eCommerce HTML5 Template
      View all products
    • Muskan Theme
    • Azedw Theme
    • Aanglo Theme
    • Jusako Template
  • Services
    • WordPress theme Customization
    • WordPress theme installation
    • Custom WP plugin development
    • Convert HTML to WP Theme
    • Convert PSD to WP Theme
    • Custom website design with Figma / Sktch / Xd
    • Convert psd / Figma / Sktch / Xd to html
    • View all services
  • Pricing
  • Blog
    • eCommerce
    • JavaScript
    • Maintenance And Code
    • Review
    • Security
    • Server
    • Snippets
    • SEO And Digital Marketing
    • Speed And Performance
    • Tutorial
    • User Experience
    • WordPress
    • All Articles
  • About
  • Support
    • Documentation
    • Create Ticket
    • Contact Us

Search

No products in the cart.

async and await in JavaScript example

JavaScript

  • By: mino-press
  • November 25, 2021
async and await in JavaScript

Async and Await in JavaScript the execution of the code is synchronous. That is, one action can performed at a time. But the behavior is asynchronous, so we have a feeling we can run several blocks of code in parallel. Thanks to the syntax that allows the script not to linger until the result of events. And instead return later, to collect the result. For example, when we send a request in Ajax, we do not wait for it to return. But perform the handling within a callback or promise, and meanwhile. The rest of the script continues to run.

Besides to callback and promise, the new syntax. That enables asynchronous behavior called Async / Await, and it is worth recognizing. That over the next few years more libraries and developers will adopt it.

In this tutorial, we will briefly mention how to use JavaScript asynchronous behavior through callbacks and promises, and then we will continue with an explanation of Async / Await.

Asynchronous code using callback

window.setTimeout( ()=> console.log('text 1'),100);
console.log('text 2');

The result is that line 2 (‘text 2’) is printed before line 1 (‘text 1’). Feel free to try it for yourself.

The second line is printed before the first line because the browser does not delay the execution of the code until the callback ends, this just continues to run, and only then returns to finish the code inside the callback.

It also works without specifying the time that the function has to wait as the second parameter passed to the method:

window.setTimeout(()=> console.log('text 1'));
console.log('text 2'); 

Why? callback!
Because the code inside the callback is executed after the rest of the script.

This is an especially useful feature when you want to wait for information coming from a remote server. For example, bringing in Ajax information using jQuery:

jQuery.get('https://phpenthusiast.com/dummy-api', (res) => console.log(res));
// The rest of the script

The rest of the script runs, instead of waiting for the information to return, if at all, from the remote server.

The API service in the example, returns a random number between 1 and 6, as in a dice roll.

Asynchronous code using promise

The newest way to get information from a remote server is through the fetch method that returns a promise, i.e. one of two possible outcomes, success or failed.

fetch('https://phpenthusiast.com/dummy-api/')
  .then((res) => console.log(res)) 
  .catch((error) => console.log(error));

Success, which means returning the requested information, is handled in the then block.

And cases of error, are handled using a catch block.

One of the benefits of using promises is that you can connect them to each other in a chain of promises that run one after the other. For example, to extract information in the JSON format that comes with the fetch() method, we will add the json() method to the string, which also returns a promise().

fetch('https://phpenthusiast.com/dummy-api/') 
  .then((res) => res.json()) 
  .then((data) => console.log(data)) 
  .catch((error) => console.log(error))

Beyond the elegance of the syntax, the errors, no matter what promises they make, are handled by the same block catch.

To promise we can thread the all() method that waits for the end of several events, for example, if we want to get information from several different sources. And in our example, we want to call the API service twice to mimic the roll of two dice:

const api = 'https://phpenthusiast.com/dummy-api/';
let dice_1 = fetch(api);
let dice_2 = fetch(api);
Promise.all([dice_1,dice_2])
// …

To extract the info efficiently you need to use the map() method:

let dice_1 = fetch(api);
let dice_2 = fetch(api);
Promise
  .all([dice_1,dice_2])
  .then(responses => Promise.all(responses.map(res => res.json())))
  .then(results => console.log(`And the result is: ${results[0].random},  ${results[1].random}`))
  .catch(()=>console.log('can\'t throw the dices'));

And the same result can be achieved using Async / Await syntax.

Asynchronous code using Async / Await

The syntax of Async / Await is simpler and more readable than a promise, and it uses the keywords async and await.

Add the async keyword before the function and the await keyword within the function.

const diceThrower = async () => {
    let dice_1 = await dice();
}

Its function calls the await returns promise:

const api = 'https://phpenthusiast.com/dummy-api/';
const dice = () => {
    return fetch(api).then(res => res.json());
}

And the await waits for all service calls to be answered to run the rest of the code:

const diceThrower = async () => {
    let dice_1 = await dice();
    let dice_2 = await dice();
    console.log(`The result is: ${dice_1.random},  ${dice_2.random}`);
}

The code is much more readable, and to handle errors we will wrap it in a try… catch:

const diceThrower = async () => {
    try {
        let dice_1 = await dice();
        let dice_2 = await dice();
        console.log(`The result is: ${dice_1.random},  ${dice_2.random}`);
    }  catch(err)  {
        console.log(err);	          
   }	
}

This is the full example:

const api = 'https://phpenthusiast.com/dummy-api/';
const dice = () => {
    return fetch(api).then(res => res.json());
}
  
const diceThrower = async () => {
    try {
        let dice_1 = await dice();
        let dice_2 = await dice();	
        console.log(`The result is: ${dice_1.random},  ${dice_2.random}`);	      
    } catch(err) { 
        console.log(err);	    	
    }
}
diceThrower();

  • twitter
  • facebook
  • WhatsApp
  • Google+
  • Pinterest
  • LinkedIn
  • Buffer
Author: Avi Aminov

Full Stack and Mobile Developer

Previous Post

how to optimize images for WordPress

Next Post

Shopify or WordPress?

0 0 votes
Article Rating
Subscribe
Login
Notify of
guest
guest
0 Comments
Inline Feedbacks
View all comments

Search


Recent post

Improving Website Speed
December 30, 2021

Improving Website Speed

How to start blogging
March 16, 2022

How to start blogging

WordPress plugins – 8 important rules before installing new plugins
January 31, 2022

WordPress plugins – 8 important rules before installing new plugins

10 Critical Mistakes Website Owners Make
December 25, 2021

10 Critical Mistakes Website Owners Make

Content Writing SEO
December 29, 2021

Content Writing SEO

Catetories

  • category image General
  • category image WordPress
  • category image Review
  • category image Tutorial
  • category image JavaScript
  • category image Security
  • category image eCommerce
  • category image Maintenance And Code
  • category image Speed And Performance
  • category image User Experience
  • category image SEO And Digital Marketing
  • category image Snippets
  • category image Server

Tags

  • CSS
  • CDN
  • archive
  • Content
  • UI
  • blogging
  • Shopify
  • SEO
  • UX
  • Review
  • WordPress
  • Tips
  • User Interface
  • Elementor
  • how to
  • wordpress security headers
  • User Experience
  • Gutenberg
  • image optimization
  • wordpress security
  • Domain
  • SVG
  • code example
  • Digital Marketing
  • domain name
  • javascript
  • Speed
  • 301
  • Woocommerce
  • Improving
  • 302
  • Security
  • plugin
  • redirect
  • Guide
  • Plugins
  • PHP
  • localStorage
  • colors
  • hook
  • Dark Mode
  • psychology
  • filter
  • Mistakes
  • gzip
  • action
  • optimization
  • compression
  • Glossary
  • promoting
  • snippet
  • hosting

Newsletter signup

Subscribe to the MinoPress newsletter to get the latest news Tutorial and guides, premium and free theme releases, updates, promotions, and more!

Please wait...

Thank you for sign up!

Logo footer logo

Our goal is to make life easy for web developers in the most optimal way, with modern and contemporary designs, (even without knowledge of code writing to succeed in creating amazing websites). Our motto is quality above all

Follow us:
  • FB
  • YU
  • LI

Contact info

  • Email: admin@minopress.com
  • Submit Ticket: Support


  • My account
  • Documentation
  • MinoPress FAQ

© 2021 WP Studio , All Rights Reserved

payment methods
  • Contact Us
  • Support
  • Terms and Conditions
  • Refund and Returns Policy

This website uses cookies to improve your experience. By using this website you agree to our Data Protection Policy.

Read more

PREMIUM WORDPRESS THEMES & SERVICES Dismiss

wpDiscuz