cft
Become a CreatorSign inGet Started

Understanding Asynchronous JavaScript

In this article, I would explain asynchronous javascript to the best of my ability to enable beginners to understand it easily.


user

Gabrielle Davidson

4 months ago | 4 min read
Follow

ux-case-study-appgrade-aplikasi-belajar-2lpar

I find Asynchronous Javascript to be one of the most confusing concepts for beginners. It wasn't easy for me to grasp either. Even though I watched a lot of tutorials and read a lot about it, it took a while before I finally understood this concept.

Therefore in this article, I would explain asynchronous javascript to the best of my ability to enable beginners to understand it easily.

JavaScript is a single-threaded language which simply means only one thing can happen at a time, this made it synchronous. This was a limitation until asynchronous javascript which involves using promises/async-await came into play.

Introduction

As earlier stated Javascript is single-threaded, which allows only one logic to be executed at a time.

Due to this setback, we couldn't perform long and complex functions because that would block javascript's main thread.

To tackle this, callbacks — which are functions passed into other functions to be called and executed later were introduced to perform asynchronous functions, but this wasn't the best approach to solving this.

Using asynchronous javascript one can perform large functions without breaking javascript's main thread.

Let's, first of all, take a look at synchronous javascript before we go deep into asynchronous javascript.

Synchronous Javascript

I am quite sure most of us have heard of the word synchronous before. what synchronous javascript simply means is executing codes in a sequence or in order.

Codes are executed sequentially, that is one after the other, each waiting for the other to be executed completely before it can execute the next in order. Synchronous javascript executes codes from top to bottom.

Let's look at the example below to enable us better understand asynchronous javascript:

Here is the result after the code executes:

From the result, you can see that the javascript engine executes the code sequentially beginning from the first line of code to the second.

This is how synchronous javascript works, it executes the first line of code which in this case is "Solomon" before it then goes down to execute the next line of code or program.

I am sure at this stage you understand how synchronous javascript works, so let's dive into the main reason for this article which is asynchronous javascript.

Asynchronous Javascript

One can describe asynchronous javascript to be the exact opposite of synchronous javascript.

Here a logic or programs are not executed sequentially or in an orderly manner but instead, they are executed based on code that is ready to be executed at that point in time.

Let's take a look at the example below to help us better understand this:

Unlike the first example, the javascript engine won't execute the code sequentially. Let's take a look at the result below:

As you can see on the code above, we have a setTimeout function that logs
Hello while the second code logs Hello Samson and then the last logs Hello Again! on the console.

The javascript engine goes through the first function which is the setTimeout function but its not able to execute it, and that is because it is set to execute after 3 seconds therefore the javascript engine does not wait, instead, it immediately moves to the second code and executes that, goes to the third code executes it before executing the setTimeout function after 3 seconds.

This is a typical example of how asynchronous javascript works, unlike the synchronous javascript that must execute each code in an orderly manner.

Let's look at the ways of executing asynchronous javascript.

Methods of executing asynchronous javascript

They are two ways of writing asynchronous javascript code. These methods include:

  1. Promises
  2. Async/Await

We are going to look at these methods of writing asynchronous javascript individually, let's start with promises.

Promises in Javascript

Promises in javascript are very similar to promises in real life. When we make a promise in real life we are certain that we are going to fulfill that promise later or in the future.

Promise in javascript works the same way. When we define a promise in javascript, it will be resolved when the time comes or it will be rejected.

A promise in javascript has three states which are :

  • Pending: initial state, before the promise succeeds or fails
  • Resolved: Completed promise
  • Rejected: Failed promise

For better understanding, let's create a promise below:

In the code above, if hungry is true, we resolve the promise by returning the data Play Game with an activity that says Play PES, else return an error object that says I am not bored.

Lets's go further into promises using the example above. We can chain a .then() and catch() method to our promise as shown in the example below:

as you can see above, we created a new function called playPES with a promise of fun, next we used the .then() method to add a function that will contain the resolve for our promise. Next, we added a .catch() method to return the error message for our promise.

But since the bored value is set to true, when we call our playPES function, we should get the results below:

Going to play PES!{ activity: 'Play PES', location:'Game studio' }.

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

Async/Await

Async/await in javascript was added in the (ES2017) release, it basically acts as a syntactic sugar that makes it easier to write promises in JavaScript. Async/await allows us to write synchronous-looking JavaScript code that works asynchronously.

An async is a function that returns a promise, if the function returns a value, the promise is resolved with the value, but if the async function throws an error, the promise is rejected with that value. Let’s look at a basic async function below:

Here, we just declared a function called favColor() which returns My favorite color is orange. Await is also an async function, it ensures that all promises returned in the function are synchronized.

In async/await javascript, try and catch methods are also used to get rejection values of async functions. So let's create an async/await function wrapped inside of a try…catch method using our earlier example:

Here we have converted our earlier example into an async/await function wrapped in a try…catch method, we logged the response in our earlier example, which returns a string I'm going to play PES at Game studio.

Conclusion

In this article, we have looked at what asynchronous JavaScript is and also how to write asynchronous JavaScript using promises and async/await. This article eye-opener on what asynchronous javascript is, you can further learn more about this concept.

You can read more about asynchronous javaScript here. Thanks for taking out time to read this piece.😎👌

Upvote


user
Created by

Gabrielle Davidson

Follow

people
Post

Upvote

Downvote

Comment

Bookmark

Share


Related Articles