Understanding and Effectively Using Asynchronous JavaScript

Understanding and Effectively Using Asynchronous JavaScript

In this JavaScript tutorial, we will learn what asynchronous JavaScript is and how to write asynchronous JavaScript using promises and async/await.

JavaScript has grown to become one of the most popular languages in the world today. It is a single-threaded language which means only one thing can be done at a time. This had previously been a limitation until asynchronous JavaScript — using promises and async/await — was added to JavaScript.

In this article, we will learn how to use asynchronous JavaScript more effectively.

Introduction

JavaScript is a single-threaded language, meaning it only allows one logic to be performed at a time, because of this you can’t perform complex long functions that will block JavaScript’s main thread. To solve this, callbacks — which are functions passed into other functions as an argument to be executed later — were used to perform asynchronous functions. Using async JavaScript, you can perform large functions without blocking the main thread of JavaScript.

To better understand this, let’s look at what we mean by synchronous and asynchronous JavaScript.

Synchronous JavaScript

Synchronous JavaScript as the name implies, means in a sequence, or an order. Here, every function or program is done in a sequence, each waiting for the first function to execute before it executes the next, synchronous code goes from top to bottom.

To better understand synchronous JavaScript, let’s look at the code below:

let a = 5;
let b = 10;
console.log(a);
console.log(b);

And here is the result:

synchronous JavaScript functions displaying function results, 5 and 10, in the console

Here, the JavaScript engine executes the first one in the equation, which in this case is 5 and then goes down to execute the second line of code, printing 10 to the console. If we add any other line of code, the JavaScript engine executes it based on the position we add it, this is what synchronous JavaScript entails, a sequential way of executing code.

Asynchronous JavaScript

Now, we have an idea on how synchronous JavaScript works, let’s talk about asynchronous JavaScript. To explain this, let’s look at the code below:

console.log("Hello.");
setTimeout(function() {
  console.log("Goodbye!");
}, 3000);
console.log("Hello again!");

Unlike our other example, JavaScript engine won’t execute the code above synchronously. Let’s take a look at the output below:

"Hello!", "Hello again!", and "Goodbye" all logged in the console

In the code, we logged Hello to our console, next we wrote a function that will log Goodbye to our console after three seconds and the last part of our code logs Hello again to our console. Here, the JavaScript engine goes through the first function and executes it, printing Hello to the console, going to the next function, it sees the setTimeout function and instead of waiting for three seconds to print the function, it goes to the last function and executes it, printing Hello again, waits for three seconds, and then executes the second function.

So with asynchronous JavaScript, the JavaScript doesn’t wait for responses when executing a function, instead it continues with executing other functions. Let’s look at ways of executing asynchronous JavaScript .

Methods for writing asynchronous JavaScript

There are two ways of writing asynchronous code in JavaScript, promises and async/await.

Promises

A promise only passes if a certain criteria is true. With JavaScript promises, we can defer a code execution until an asynchronous request is completed, this way other functions can keep running without blocking the thread.

Promises are a new way of writing asynchronous JavaScript, its usually an object with three main states, which includes:

  • Pending — the initial state of the program before the promise passes or fails
  • Resolved — a successful promise
  • Rejected — a failed promise

To better understand this, let’s create a promise below:

const hungry = true;
const eat = new Promise(function(resolve, reject) {
  if (hungry) {
      const fastfood = {
        activity: 'Cook noodles',
        location: 'Market Square'
      };
  resolve(fastfood)
  } else {
    reject(new Error('Not hungry'))
    }
});

In the code above, if hungry is true, resolve the promise returning the data with a fastfood with an activity that says Cook noodles, else return an error object that says Not hungry.

Using a promise

Let’s push this further and use the promise we initialized above, we can chain .then() and a .catch() method to our Promise below:

const willEat = function() {
  eat
    .then(function(hungry) {
      console.log('Going to eat noodles!')
      console.log(hungry)
    })
    .catch(function(error) {
        console.log(error.message)
    })
}

willEat();

In the code above, we created a new function called willEat() with a promise of eat, next we used the .then() to add a function that will contain the resolve for our promise. We then added a .catch() method to return the error message in our promise.

Since the hungry value is true, when we call our willEat() function, we should get the results below:

Going to eat noodles!
{
  activity: 'Cook noodles',
  location: 'Market square'
}

If we change the value of hungry to false, our promise will display the status for a failed promise which in our case will be not hungry. We can push our promises further by creating a new promise that’d take parameters from our earlier examples:

const foodTour = function(fastfood) {
  return new Promise(function(resolve, reject) {
    const response = `I'm going on a food tour at
        ${fastfood.location`;

    resolve(response)
  });
}

In the code above, we created a new promise called foodTour that takes the fastfood value from earlier example, and resolves a response with a template string on the fastfood location in our earlier example.

javascript programming developer web-development

Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

Why Web Development is Important for your Business

With the rapid development in technology, the old ways to do business have changed completely. A lot more advanced and developed ways are ...

Important Reasons to Hire a Professional Web Development Company

    You name the business and I will tell you how web development can help you promote your business. If it is a startup or you seeking some...

What Garbage Collection in JavaScript Is and How It Works

JavaScript values are allocated when things are created (objects, Strings, etc.) and freed automatically when they are no longer used. This process is called Garbage collection.

What Javascript Spread Operator is, How It Works and How to Use It

JavaScript spread operator is one of the more popular features that were introduced in ES6. This tutorial will help you understand it. You will learn what spread operator is and how it works. You will also learn how to use it to copy and merge arrays and object literals, insert data and more.

Top 10 Web Development Trends in 2020 | Web Development Skills

Top 10 Web Development Trends in 2020 will provide you with a detailed list of the trends which are currently being noticed. Upskilling to these trends will help you in landing onto better jobs in 2020-2021.