Sign in

How to handle Async code in JavaScript?

When you start studying JavaScript, you would hear “JavaScript is Synchronous.” and then, you would be like “….?”. Don’t worry! It happened to me too! Today, I will dive into what is Synchronous and Asynchronous, and how to control them.

01 — What is Synchronous and Asynchronous?

Synchronicity means “doing something at the same time, and happening at the same time”.

Asynchronous means “doesn’t happen at the same time”.

02 — Is JavaScript Synchronous?

First, JavaScript is single-threaded language. In other words, JavaScript is not able to do something at the same time. JavaScript runs codes in orders. However, JavaScript is able to continue to work when JavaScript is asking other program (like database) to do something. In this, JavaScript is Synchronous.

  • JavaScript is not able to do concurrent— one thing at moment

03— How to handle Asynchronous code?

There are different ways to handle the async code. Those are callbacks, promises, and async/await.

Before all of those function, let’s see how JavaScript work:

I created the object of users and two functions, getUsers() to print out all users in the object and addUser() to add new user.

The setTimeout() method calls a function or evaluates an expression after a specified number of milliseconds.

Tip: 1000 ms = 1 second.

Let’s check output:

We only got two users. Because, new user has been set to be added in 2 seconds. So JavaScript didn’t wait new user to be added. This is Asynchronous.

Now time to see how to handle the async code.

Callbacks

In JavaScript, functions are objects. We could pass functions as parameters to other functions and call them inside of the other functions.

Callback is a function that is passed to another function.

Let’s see an example of callback function:

I gave getUser() as second parameter and call it inside of addUser(). So addUser() runs first.

Let’s see output:

We got the third user too! It means we could control asynchronous .

However, there is problems with callbacks too. It is called “Callback Hell”.

It is also known as Pyramid of Doom. It is like nesting functions within functions within functions ………. and you create a Pyramid of code.

Let’s see an example of Callback Hell:

The code changes the background color in order.

What do you think? Does it clean code?

This is “Callback Hell”. The function calls another function, and another function calls other function……We can not say “this is a clean code!”.

To avoid this hell, we would use second and third ways to handle the async code.

Promise

A promise in JavaScript is similar to a promise in real life. Once we promise something with JavaScript, he will keep the promise!

Promise is an object which represents the eventual completion or failure of an asynchronous operation.

You can easily handle Asynchronous by using a promise!

Fiest, There are 3 states of the Promise object:

  • Pending: Initial State, before the Promise succeeds or fails.

For example, pending mode is when we are waiting to receive the data we request from the server.

If we successfully to get the data from the server, the Promise will be resolved mode. But if we don’t get the data, then the Promise will be rejected mode.

Let’s see how to create a Promise:

The Promise has two parameters, first one for success (resolve) and second one for fail(reject).

In this code, we will get resolve() if status is true. If it’s false, we will get reject(‘Failed’).

Let’s see output:

We got nothing. This is not an error!

To use the promise, we need to use then() for resolve and catch() for reject methods.

Let’s see the code with then():

output:

We got all the users! In this code, status is true, so resolve() is called, then() is called, and then getUsers() is called.

This is a little confusing. However, it would be very easy once you understand how it works!

Now, let’s see when status is false:

We need catch() for reject as I said.

output:

reject() is called, catch() is called, and then we got error message in console!

Async/Await

Await is basically syntactic sugar for a Promise. It is easier to use and more clear than a Promise.

Let’s see how to create:

Tip: async function returns promise object

output:

I didn’t change most of codes. The await is a way to handle responses. It not like a different way to write.

So we have the same object and same function called getUser(). Just not in this picture.

Tip: The await keyword is only valid inside async functions, a SyntaxError will be raised if used outside async functions.

04-Conclusion

  • JavaScript is not able to do concurrent, but JavaScript is Synchronous

They are pretty confusing. I am pretty sure that a lot of people get stuck with these topics when they are studying JavaScript. I want you to understand the above two things. It will help you a lot I guess. I hope you enjoyed this article, and learned something new.

Starter FrontEnd Developer based in Vancouver, Canada.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store