Javascript — Asynchronous & Synchronous

Kevin Huang
5 min readApr 5, 2021

--

While on my journey to become a web developer, there was always one thing that I could not wrap my head around and that was async-await and promises. I understood what they did and how they were used. I used it in one of my first applications, but I only had a general idea on how it works. I am writing this blog post to help people who are new to coding and help them get an introductory sense of what async/sync is in JavaScript.

Callback and CallStacks

First we need to understand how JavaScript runs on the browser. If we have the code:

This piece of code runs synchronously. Just by taking a look at this code, we know the output for this will be “start” -> “we’re in the middle” -> “end”. By running the file this is the output:

Simple so far right? What happens when we try to run code that might take longer? For example, what if we’re doing a fetch request and the fetch takes 5 seconds? Will the compiler stop everything and wait for the fetch request to finish before proceeding to the next block of code?

In the following example, I will be using setTimeout() to simulate a fetch request. If we take a look at this snippet: setTimeout(()=>{ console.log("2. simulating fetch request"},3000) we are setting a timeout for this console.log to run. I’ve set it to 3000ms which translate to 3seconds.

From our first example we should expect this to output “1. start” -> “2. simulating fetch request” -> “3. end” right? Let’s take a look at what the output on the terminal is.

What?? That’s not the case? That’s because even though by default, JavaScript runs synchronously, the browser is smart enough to create a new thread and leave it in the background and process the block of code. Imagine you’re on a website and you were not able to interact with the website until it finishes running the code. That would be really inconvenient!

Issues running synchronous JavaScript

Suppose we have this block of code:

Based on the second example, we should see “1. start” -> “3. end” -> userName: “Kevin”.

So why are we getting undefined? Well, because since the getUserInfo function takes 2 seconds to return our userName object, JavaScript already set aside memory for the const user on line 9 however, it’s not initialized with any data yet because we set the getUserInfo to return the username after 2 seconds. So when the compiler is running the console.log on line 11, the variable exists however, the data from the function has not finished processing.

Introducing the infamous callback hell

One way we can bypass the undefined variable is by creating a callback.

By creating a callback function we’re able to get the users information.

However, what happens if we need to create multiple fetches? What if we need to get more data back from the server. Let’s say we need to get more than just the users name?

As you can see, if we’re fetching multiple times for different sets of data, we have to nest multiple callbacks. This leads to messy and unreadable code. Thus the infamous callback hell.

Introducing promises & .then

A promise in JavaScript is an object that may produce a single value some time in the future. Just like a promise in real life it ‘promises’ to return something. It can be in 1 of the 3 possible states: fulfilled, rejected, or pending.

Let’s start by refactoring our ugly code to what it would look like if we used promises.

Much easier to read!

Starting on line 40, we call the function getUserInfo and within that function, we wrote a promise that will return a console.log an object that contains the userName. In the next line .then(userName => getUserFriends(userName) we used the data in the promise to call another function getUserFriends . By using .then we can chain multiple functions that require data from previous promises!

Async functions and await

Let’s re-refactor our code once again using async await functions!

Notice the function getAllData has the keyword async . In JavaScript, when using the await keyword you must tell JavaScript that this is going to be an asynchronous function or you will get an error.

Conclusion

Hopefully this gave you some basic understanding on what async/sync is. While I didn’t dive too deep into the nitty gritty of it, my goal was to introduce async await and promises to you to help you get a better understanding of it.

resources

--

--