Skip to main content

Introduction

Before we start

One word that you will hear a lot in JavaScript is asynchronous (shortly async). It is a word that is used to describe a lot of things, but what does it mean 🤔 ?

The async concept becomes a bit confusing if you are a beginner. In this article, I will be showing you that the concept is not difficult as it sounds.

And I will be discussing with you the callback, promises, async/await and other terms related to async in JavaScript.

How JavaScript works?

JavaScript is a single-threaded language. It means that it can only do one thing at a time. It can only execute one line of code at a time.

console.log("Hello");
console.log("World");

In the above example, the JavaScript engine will first execute the first line and then the second line of code. It will not execute the second line of code until the first line of code is executed. This is synchronous code.

Let's see what synchronous and asynchronous is.

Synchronous vs Asynchronous

Synchronous Code

Sync code executes immediately, line by line, and does not wait (depends) for any other code to execute.

console.log("Hello");
console.log("World");

In the above example, console.log("Hello") will execute first, and then console.log("World") will execute right away.

Asynchronous Code

Asynchronous code does not execute immediately. It executes after some time. Async code can be an API call, a database query, a file read, a timeout function, or any other long-running task. Check out the following example:

console.log("Hello");
setTimeout(() => {
console.log("World");
}, 1000);

In the above example, console.log("Hello") will execute first, and then console.log("World") will execute after 1 second.

note
What is setTimeout()

The setTimeout() is an async function which takes two arguments: a callback function and a time in milliseconds. It executes the callback function after the specified time.

Conclusion

In this article, we learned about synchronous and asynchronous code. We also learned about the JavaScript engine and how it executes code. We will be learning more about asynchronous code in the next articles.